if exists(select 1 from sysobjects where name='tr_rm_payflow')
  drop TRIGGER tr_rm_payflow
go

create trigger tr_rm_payflow on t_rm_payflow 
for insert
as
begin
  -- 是否传输明细数据到日结表
--  if (select remote_flag from inserted) = '1' RETURN
								
  declare @ls_casher 			char(4),     -- 收银员
	      @ls_flowNo 			char(14),        -- 销售号
	      @ln_flowId 			numeric(3,0),    -- 销售序号
	      @gs_branchNO 			char(6),       -- 仓库编码
	      @ls_branchNO 			char(6),       -- 仓库编码
	      @ln_saleAmt 			numeric(16,4),  -- 销售金额
	      @ln_payAmt 			numeric(16,4),   -- 付款金额
	      @ls_payWay 			char(3),         -- 付款方式--(2-->3)
	      @ls_coinNO 			char(3),         -- 币种
	      @ln_coinRate 			decimal(6,4),  -- 币种汇率
	      @ldt_payDateTime 		datetime,  -- 付款时间
	      @ls_saleWay 			char(1),        -- 销售方式
	      @ls_operDate 			char(10),      -- 字符型日期（当天），格式为：yyyymmdd
	      @ls_vipNO 			varchar(20),      -- 会员卡号
	      @ls_cardNO 			varchar(20),     -- 储值卡号
	      @ls_casherExistFlag 	char(1),-- 收银员在收银日结表(t_rm_casher_daySum)中是否已存在标志，'0'=不存在；'1'=已存在
	      @ln_scale  			decimal(10,2),
	      @ln_nativeamt 		numeric(16,4),
	      @gs_counter_ctrl      char(1),        --是否合同专柜管理
	      @gs_shift_ctrl        char(1),        --是否班次管理
	      @ls_shift_no          char(9),        --班次号
	      @ls_shift_date        char(10),       --班次日期
	      @ls_shift_str         char(1),        --班次号(1,2,3,4)
	      @ls_counterExistFlag  char(1),
	      @ls_shiftExistFlag    char(1),      
	      @ls_counter_no        char(4),        --柜台号
	      @ln_sale_amt          numeric(16,4),  --销售金额(本位币)
	      @ln_ret_amt           numeric(16,4),  
	      @ln_bankcard_amt      numeric(16,4),  --银行卡销售额
	      @ls_g_branch_no       varchar(10) ,    --总部机构代码
          @ls_memo              varchar(255),     --订金支付说明
	      @ls_ciceroni_id        varchar(6) ,    --导游编号
          @ls_ciceroni_no        varchar(10),     --牌号
          @trans_type            char(3),         --业务类型
		  @ls_oper_type         char(1),
          @remark              varchar(255)

  DECLARE inserted_cursor CURSOR FOR 
select  flow_no,	    flow_id,	    oper_id,	    branch_no,	    pay_amount,	    sale_amount,	    pay_way,
	    coin_no,	    coin_rate,	    oper_date,	    sell_way,	    vip_no,	     card_no,	     shift_no,	     counter_no,         rtrim(memo) , ciceroni_id , ciceroni_no,trans_type,
        remark
  from inserted 
	where remote_flag <> '1' or remote_flag is null

 -- 是否传输明细数据到日结表
--  if ( @remote_flag = '1' ) RETURN --独立分店上传时直接返回不处理,且配送中心不传

OPEN inserted_cursor

FETCH inserted_cursor 
into @ls_flowNo ,	    @ln_flowid,	    @ls_casher,	    @ls_branchNO,	    @ln_payAmt,    @ln_saleAmt,	    @ls_payWay,
	    @ls_coinNO,	    @ln_coinRate,	    @ldt_payDateTime,	    @ls_saleWay,	    @ls_vipNO ,	    @ls_cardNO ,
	    @ls_shift_no ,	    @ls_counter_no ,        @ls_memo  , @ls_ciceroni_id , @ls_ciceroni_no, @trans_type,@remark
WHILE @@FETCH_STATUS = 0
BEGIN
 ----调用订金来付款结算时不用再做以下操作，因为在付订金时就已经写了一次收银员日结表等，此时应直接返回
  if @ls_payway='ORD' and @ls_saleWay='A' and @ls_memo='ORD_PAY'  goto rtn

  if @ls_memo='外送回款'  
	update t_rm_salecust_send set pay_flag ='1' where flow_no = @ls_flowNo

  if @trans_type = 'TPP' or @trans_type = 'LEV'
     begin
     	select @ls_oper_type = '1'
     end
  else
     begin
	select @ls_oper_type = '0'
     end 

 
  select @ls_g_branch_no = sys_var_value 
	from t_sys_system where lower(sys_var_id)='g_branch_no'


  if @ls_branchNO is null or @ls_branchNO = '' 
	select @gs_branchNO = @ls_g_branch_no
  else
	select @gs_branchNO = left(@ls_branchNO,2) 
 
  -- 得到系统是否进行班次管理（在系统表中）
  select @gs_shift_ctrl = sys_var_value from t_sys_system where lower(sys_var_id)='shift_ctrl'

  -- 转换字符型日期（当天），格式为：121=yyyy-mm-dd
  select @ls_operDate=convert(char(10),@ldt_payDateTime,121)

  -- 当前机构或总部托管的分部上传的POS流水才可写收银员日结表  wujs 2004-11-13,独立管理分部的收银日报单独上传到总部
  -- Modified by huangc  2005-01-10  POS分部	
  if (@ls_g_branch_no = @gs_branchNO) or 
     Exists (select branch_no from t_bd_branch_info where property = 0 and branch_no = @gs_branchNO and (trade_type = '0' or trade_type = '4'))
  begin
     -- 查找在收银员日结表(t_rm_casher_daySum)中是否已存在
     if not exists(select * from t_rm_casher_daysum
        where (oper_date=@ls_operDate and casher_no=@ls_casher and branch_no=@gs_branchNO and pay_way=@ls_payWay and sale_way=@ls_saleWay and coin_no=@ls_coinNO)) -- 不存在
          select @ls_casherExistFlag='0'
     else  -- 已存在
          select @ls_casherExistFlag='1'

      -- 写收银员日结表(t_rm_casher_daySum).............................................start num3记录收款方式的次数20180804
     if @ls_casherExistFlag='0' -- 收银员不存在，增加  -- 注：oper_type='0',缺省只为收银员
        insert into t_rm_casher_daysum(oper_date,casher_no,branch_no,sell_amt,real_amt,sale_way,pay_way,coin_no,oper_type,other1,other2,other3,num3)
	values(@ls_operDate,@ls_casher,@gs_branchNO,0,@ln_payAmt,@ls_saleWay,@ls_payWay,@ls_coinNO,@ls_oper_type,null,null,null,1)
     else
        -- 收银员已存在，更新
        update t_rm_casher_daysum set real_amt=real_amt+@ln_payAmt, com_flag='0',num3=num3+1
           where (oper_date=@ls_operDate and casher_no=@ls_casher and branch_no=@gs_branchNO and pay_way=@ls_payWay and sale_way=@ls_saleWay and coin_no=@ls_coinNO)
        -- 写收银员日结表(t_rm_casher_daySum).............................................end
  end

  
  --if @gs_shift_ctrl = '1' or (isnull(@ls_shift_no,'') <> '' and Exists (select branch_no from t_bd_branch_info where property = 0 and branch_no = @gs_branchNO and (trade_type = '0' or trade_type = '4')))    -- 是否班次管理
  --begin  --MAHW 只要有班次，就写班次数据，不受开关控制 QS-120717-228289 
	  -- 查找在班次日结表(t_rm_shift_daysum)中是否已存在
	if len(isnull(@ls_shift_no,'')) > 0 --班次为空则不处理liug 2009-02-23
	begin		  
	  select @ls_shift_date = substring(@ls_shift_no,1,4)+'-'+substring(@ls_shift_no,5,2)+'-'+substring(@ls_shift_no,7,2)
	  select @ls_shift_str  = substring(@ls_shift_no,9,1)
	
	  if not exists(select* from t_rm_shift_daysum
		 where (oper_date=@ls_shift_date and casher_no=@ls_casher and shift_no=@ls_shift_str and branch_no=@gs_branchNO and pay_way=@ls_payWay and sale_way=@ls_saleWay and coin_no=@ls_coinNO)) -- 不存在
		 select @ls_shiftExistFlag='0'
	  else  -- 已存在
		 select @ls_shiftExistFlag='1'
	
	  -- 写班次日结表(t_rm_shift_daysum).............................................start
	  if @ls_shiftExistFlag='0' -- 班次不存在，增加  
	         -- modified by wujs 2005-09-01 other1 置第本班次一笔交易时间 other2 为本班次最末一笔交易时间
		 insert into t_rm_shift_daysum(oper_date,casher_no,shift_no,branch_no,sell_amt,real_amt,sale_way,pay_way,coin_no,oper_type,other1,other2,other3) values(
		     @ls_shift_date,@ls_casher,@ls_shift_str,@gs_branchNO,0,@ln_payAmt,@ls_saleWay,@ls_payWay,@ls_coinNO,@ls_oper_type,convert(varchar(19),getdate(),120),convert(varchar(19),getdate(),120),null)
	  else
		 -- 班次已存在，更新
		 update t_rm_shift_daysum set real_amt=real_amt+@ln_payAmt, com_flag='0',other2=convert(varchar(19),getdate(),120)
			where (oper_date=@ls_shift_date and casher_no=@ls_casher and shift_no=@ls_shift_str and branch_no=@gs_branchNO and pay_way=@ls_payWay and sale_way=@ls_saleWay and coin_no=@ls_coinNO)
	  -- 写班次日结表(t_rm_shift_daySum).............................................end
	end
  --end
  

  -- 会员卡消费,更新会员卡消费总额
 
 if (@ls_vipNO is not Null) AND (@ls_vipNO <> '')
  begin
       -- 只记录正常销售和退货时记录
      if (((@ls_saleWay = 'A') or (@ls_saleWay = 'B') or (@ls_saleWay = 'D') ) and @ls_payWay <> 'CHG')
      begin
			-- 退货时记录负数 modified by lihg 2006-10-31
			if @ls_saleWay = 'B' or @ls_saleWay = 'D'
				select @ln_payAmt = -1 * @ln_payAmt * @ln_coinRate
		
		    -- 分部上传的付款流水时不可以再生成会员付明细,会员付款明细单独上传. wujs 2004-11-13
			if @ls_g_branch_no = @gs_branchNO or Exists (select branch_no from t_bd_branch_info where property = 0 and branch_no = @gs_branchNO and trade_type = '4')
			begin
				if Exists (select * from t_rm_card_paylist where flow_no = @ls_flowNo and card_id = @ls_vipNO and card_type='1')
					update t_rm_card_paylist set amount = amount + @ln_payAmt
						where flow_no = @ls_flowNo and card_id = @ls_vipNO and card_type='1'
				else
			        insert into t_rm_card_paylist(flow_no, card_type, card_id, amount, pay_time,branch_no,other2)
			  	      values(@ls_flowNo, '1', @ls_vipNO, @ln_payAmt , @ldt_payDateTime,@gs_branchNO,@remark)
			  	      
			  	      
			  	--零钱变动处理	zhouzx	2018-5-17
			  	if exists( 
			  		select b.* from t_rm_vip_info a, t_rm_vip_type b
					where a.card_type = b.type_id
					and b.saving_flag = '0'
					and a.card_id =  @ls_vipNO
				) 
				begin	
					if @trans_type = 'LEV'	
						insert into mess_t_vip_message(mess_type,branch_no,card_id,savelist_amt,oper_type,send_flag) 
						values('L',@gs_branchNO,@ls_vipNO,@ln_payAmt,'4','0')	
						
					if @ls_payWay = 'LEP'		
						insert into mess_t_vip_message(mess_type,branch_no,card_id,savelist_amt,oper_type,send_flag, flow_amt) 
						values('L',@gs_branchNO,@ls_vipNO,@ln_payAmt,'5','0', @ln_payAmt)
				end
				
				
				
			end
      end
  end

  --导游功能
  if ( @ls_ciceroni_id is not NUll ) AND ( @ls_ciceroni_id <> '' ) AND ( @ls_ciceroni_no is not NUll ) AND ( @ls_ciceroni_no <> '' )
	begin
		if not exists( select * from t_bd_ciceroni_no_flow where Ciceroni_id = @ls_ciceroni_id and ciceroni_no = @ls_ciceroni_no AND
			Branch_no = @gs_branchNO and flow_no = @ls_flowNo ) --不存在
		insert into t_bd_ciceroni_no_flow( Ciceroni_id ,     ciceroni_no,      Branch_no,    flow_no,    Oper_id ,   Oper_date ,Branch_id )
								   values( @ls_ciceroni_id , @ls_ciceroni_no , @gs_branchNO ,@ls_flowNo ,@ls_casher, @ldt_payDateTime, @ls_branchNO  )
			 
	end
	--chenhd 2017-09-11，礼券记录
	if @ls_payWay = 'SHP' and @ls_saleWay = 'A'
	BEGIN
		IF (select isnull(sys_var_value,0) from t_sys_system where sys_var_id = 'pos_checkgwq') = '1'
		BEGIN
			UPDATE t_rm_gift_certificate 
			SET status = '2', flow_no = @ls_flowNo, pay_oper = @ls_casher, pay_date = @ldt_payDateTime, pay_branch = @ls_branchNO
			WHERE giftcert_no = @ls_cardNO
		END
	END
FETCH inserted_cursor 
into @ls_flowNo ,	    @ln_flowid,	    @ls_casher,	    @ls_branchNO,	    @ln_payAmt,    @ln_saleAmt,	    @ls_payWay,
	    @ls_coinNO,	    @ln_coinRate,	    @ldt_payDateTime,	    @ls_saleWay,	    @ls_vipNO ,	    @ls_cardNO ,
	    @ls_shift_no ,	    @ls_counter_no ,        @ls_memo , @ls_ciceroni_id , @ls_ciceroni_no,@trans_type,@remark
 
end

rtn:
CLOSE inserted_cursor
DEALLOCATE inserted_cursor
end
go