if exists(select * from sysobjects where name = 'f_monthoflastday' and xtype = 'fn')
  drop function f_monthoflastday
go
create function f_monthoflastday(@sdate varchar(10)) returns int
as
begin
  declare @iRtn int
  select @iRtn = DATEPART(DD,DATEADD(mm,DATEDIFF(mm,0,@sdate) + 1,-1))
  return @iRtn
end
go

if exists(select * from sysobjects where name = 'f_continuedays' and xtype = 'fn')
  drop function f_continuedays
go
create function f_continuedays(@sourcestr varchar(8000),@idays int) returns int
as
begin
  declare @str varchar(8000)
  declare @iRtn int
  if @idays = 1 
  begin
    return (0)
  end
  set @str = substring(@sourcestr,1,@idays - 1)
  set @str = reverse(@str)
  set @iRtn =charindex('0',@str)
  if @iRtn = 0
  begin
    set @iRtn = len(@str)
  end
  else
  begin
    set @iRtn = @iRtn - 1
  end

  return @iRtn
end
go

if exists(select * from sysobjects where name = 'f_continueenddays' and xtype = 'fn')
  drop function f_continueenddays
go
create function f_continueenddays(@sourcestr varchar(8000),@idays int) returns int
as
begin
  declare @str varchar(8000)
  declare @iRtn int
  if @idays >= 31
  begin
    return (0)
  end
  set @str = substring(@sourcestr,@idays + 1,31-@idays)
  set @iRtn =charindex('0',@str)
  if @iRtn = 0
  begin
    set @iRtn = len(@str)
  end
  else
  begin
    set @iRtn = @iRtn - 1
  end

  return @iRtn
end
go

/*
declare @psmsg varchar(2000)
exec p_create_askdata '','','', @psmsg out
print (@psmsg)
*/
--自动生成要货数据
if exists(select * from sysobjects where name='p_create_askdata' and xtype='p')
  drop procedure p_create_askdata
go
create procedure p_create_askdata
(					
  @psorgcode varchar(10),
  @psasktype varchar(1),
  @psparams varchar(200),
  @psmsg varchar(2000) out
)
as
  declare @sorgcode varchar(10) 
  declare @sisdbdeploy varchar(1)
  declare @sorgtype varchar(1)
  declare @sver varchar(1)
  declare @sdate varchar(10)
  declare @stime varchar(8)
  declare @ssql varchar(8000)
  declare @saskbgndate varchar(10)
  declare @saskenddate varchar(10)
begin
  set @psmsg=''
  select @sver=itemvalue from t_syscfg where section='SYSTEM' and itemname='VER'
  if @sver <> '1'
  begin
    set @psmsg = '单店版不生成要货数据'
	return (1)
  end
  select @sisdbdeploy=isdbdeploy,@sorgtype=orgtype from t_shop where orgcode=@sorgcode
  
  if exists(select * from sysobjects where name = 'tmpaskdata_param' and xtype = 'U')
    drop table tmpaskdata_param
  create table tmpaskdata_param(
    plucode varchar(20) not null default('*'),  
	orgcode varchar(10) not null default('*'),
	asktype varchar(1) not null ,
    askdate varchar(31) not null default(''), 
	promdesc varchar(100) null,
	askbgndate varchar(10)null,
	askenddate varchar(10) null,
    dhdays int not null default (0),  
    safedays int not null default (0), 
    askcycle int not null default (0), 
    predays int not null default (0),   
    cgmode varchar not null default ('1'),
    judgecnt numeric(19,4) not null default (0),
	continuedays int not null default (0),
	continueenddays int not null default (0), 
	gcount numeric(19,4) not null default (0),
	ccount numeric(19,4) not null default (0),
	onwaycount numeric(19,4) not null default (0), 
	dms numeric(19,4) not null default (0),
	dscdms numeric(19,4) not null default (0),
	caldms numeric(19,4) not null default (0),
	askcounts numeric(19,4) not null default (0)
	constraint [REDACTED]primary key nonclustered
	(
		plucode,orgcode
	)
  )
  --print(convert(varchar(100),getdate(),120) + '    begin fill data')
  declare @iDay integer
  set @iDay = datepart(dd,getdate())
  insert into tmpaskdata_param(orgcode,plucode,asktype,askdate,dhdays,safedays,askcycle,predays,cgmode,judgecnt,continuedays,continueenddays,gcount,ccount,dms,dscdms,caldms) 
	select o.orgcode,o.plucode,a.asktype,a.askdate,a.dhdays,a.safedays,a.askcycle,a.predays,o.cgmode,o.judgecnt,
	       dbo.f_continuedays(askdate,@iDay),dbo.f_continueenddays(askdate,@iDay),o.gcount,o.ccount,o.dms,o.dscdms,o.dms
	from t_plu_org o ,t_pluask_param a , t_shop s
	where a.asktype = '2' and o.plucode = a.plucode and o.orgcode = s.orgcode
	and substring(a.askdate,@iDay,1) = '1' 
	and o.isright = '1' and o.isask = '1' and o.mngstock = '1' 
	and s.orgtype <> '2'
	and s.status = '1'
	and not exists(select 1 from tmpaskdata_param where plucode = o.plucode and orgcode = o.orgcode)
	and not exists(select plucode from t_ask_head,t_ask_body
					where t_ask_head.billno=t_ask_body.billno
						and t_ask_body.plucode=o.plucode and t_ask_head.orgcode = o.orgcode
						and t_ask_head.lrdate = convert(varchar(10),getdate(),120)
						and t_ask_head.asktype = '2')
	and o.orgcode = case @psorgcode when '' then o.orgcode else @psorgcode end

	insert into tmpaskdata_param(orgcode,plucode,asktype,askdate,dhdays,safedays,askcycle,predays,cgmode,judgecnt,continuedays,continueenddays,gcount,ccount,dms,dscdms,caldms) 
	select o.orgcode,o.plucode,a.asktype,a.askdate,a.dhdays,a.safedays,a.askcycle,a.predays,o.cgmode,o.judgecnt,
	       dbo.f_continuedays(askdate,@iDay),dbo.f_continueenddays(askdate,@iDay),o.gcount,o.ccount,o.dms,o.dscdms,o.dms   
	from t_plu_org o ,t_pluask_param a , t_shop s  ,t_plu p ,t_gclass c
	where a.asktype = '1' and o.plucode = p.plucode and o.orgcode = s.orgcode 
	and o.cgmode = '2' and p.clscode = c.clscode and c.uppercode1 = a.plucode
	and substring(a.askdate,@iDay,1) = '1' 
	and o.isright = '1' and o.isask = '1' and o.mngstock = '1' 
	and s.orgtype <> '2'
	and s.status = '1'
	and not exists(select 1 from tmpaskdata_param where plucode = o.plucode)
	and not exists(select plucode from t_ask_head,t_ask_body
					where t_ask_head.billno=t_ask_body.billno
						and t_ask_body.plucode=o.plucode and t_ask_head.orgcode = o.orgcode
						and t_ask_head.lrdate = convert(varchar(10),getdate(),120)
						and t_ask_head.asktype = '1')
	and o.orgcode = case @psorgcode when '' then o.orgcode else @psorgcode end

	insert into tmpaskdata_param(orgcode,plucode,asktype,askdate,dhdays,safedays,askcycle,predays,cgmode,judgecnt,continuedays,continueenddays,gcount,ccount,dms,dscdms,caldms) 
	select o.orgcode,o.plucode,a.asktype,a.askdate,a.dhdays,a.safedays,a.askcycle,a.predays,'1',o.judgecnt,
	       dbo.f_continuedays(askdate,@iDay),dbo.f_continueenddays(askdate,@iDay),o.gcount,o.ccount,o.dms,o.dscdms,o.dms     
	from t_plu_org o ,t_pluask_param a ,t_shop s  
	where a.asktype = '0' and o.orgcode = s.orgcode and(o.cgmode = '0' or o.cgmode = '1')
	and substring(a.askdate,@iDay,1) = '1' 
	and o.isright = '1' and o.isask = '1' and o.mngstock = '1' 
	and s.orgtype <> '2'
	and s.status = '1'
	and not exists(select 1 from tmpaskdata_param where plucode = o.plucode)
	and not exists(select plucode from t_ask_head,t_ask_body
					where t_ask_head.billno=t_ask_body.billno
						and t_ask_body.plucode=o.plucode and t_ask_head.orgcode = o.orgcode
						and t_ask_head.lrdate = convert(varchar(10),getdate(),120)
						and t_ask_head.asktype = '0')
	and o.orgcode = case @psorgcode when '' then o.orgcode else @psorgcode end
	--print(convert(varchar(100),getdate(),120) + '    end fill data');

	delete a
	from tmpaskdata_param a,t_plu b
	where (a.plucode = b.plucode and b.plustatus = '2')

  	delete a
	from tmpaskdata_param a
	where exists(select billno from t_ask_head
					where t_ask_head.orgcode = a.orgcode
						and t_ask_head.lrdate between convert(varchar(10),dateadd(dd,-1*continuedays,getdate()),120) and convert(varchar(10),getdate(),120)
						and t_ask_head.asktype = a.asktype)
  --print(convert(varchar(100),getdate(),120) + '    end delete data');
  if exists(select * from sysobjects where name = 'tmpaskdata_onway' and xtype = 'U')
    drop table tmpaskdata_onway
  create table tmpaskdata_onway(
    plucode varchar(20) not null default(''),  
	orgcode varchar(10) not null default(''),
	onwaycount numeric(19,4) not null default (0)
	constraint [REDACTED]primary key nonclustered
	(
		plucode,orgcode
	)
  )
  insert into tmpaskdata_onway(orgcode,plucode,onwaycount)
  select a.orgcode,a.plucode,counts
  from
	  (select orgcode,plucode,sum(counts) as counts
	  from (
		  select orgcode,plucode,sum(b.counts) as counts from t_accept_head a join t_accept_body b on a.billno = b.BillNo
		  where (a.billtype = '3') and isnull(a.rzdate,'')='' 
		  group by orgcode,plucode
		  union all
		  select orgcode,plucode,sum(b.counts) as counts from t_order_head a join t_order_body b on a.billno = b.BillNo
		  where iszs = '1'  and isnull(a.rzdate,'')<>''
			and not exists(select 1 from t_accept_head where billtype = '2' and orderno = a.billno and isnull(rzdate,'') <> '')
		  group by orgcode,plucode
		  union all
		  select orgcode,plucode,sum(b.counts) as counts from t_outtrans_head a join t_outtrans_body b on a.billno = b.BillNo
		  where (a.isout = '0') and isnull(a.rzdate,'')='' 
		  group by orgcode,plucode
	  )src1
	  group by orgcode,plucode
	  )a,tmpaskdata_param b where a.plucode = b.plucode and a.orgcode = b.orgcode
  update a 
  set a.caldms = a.dscdms,
      a.promdesc = b.promdesc
  from tmpaskdata_param a, dbo.t_bcbiz_head h, dbo.t_bcbiz_body b
  where a.plucode = b.plucode and (a.orgcode = b.orgcode or b.orgcode = '*') and h.billno = b.billno and h.qrstatus <>'0'
    and dateadd(dd,a.predays,getdate()) between b.prombgndate and b.promenddate
  update a
    set a.onwaycount = isnull(b.onwaycount,0),
	    a.askcounts = ceiling(a.caldms *  (askcycle + dhDays + SafeDays) - gcount - ccount - IsNull(b.onwaycount,0))
  from tmpaskdata_param a left join tmpaskdata_onway b on a.plucode = b.plucode and a.orgcode = b.orgcode


  delete a
  from tmpaskdata_param a ,t_plu p,t_gclass c 
  where a.askcounts <= 0 and a.plucode = p.plucode and p.clscode = c.clscode
    and c.uppercode1 = '2032'

  update tmpaskdata_param
  set askcounts = 0
  where askcounts < 0

  update a
    set a.askcounts = ceiling(a.askcounts/b.askcnt)*b.askcnt
  from tmpaskdata_param a ,t_plu  b
  where a.plucode = b.plucode and b.askcnt <> 0 and (a.askcounts % b.askcnt) <> 0

  update a 
  set a.cgmode = case when askcounts < a.judgecnt then '1' else '2' end
  from tmpaskdata_param a
  where a.asktype = '2' and a.cgmode = '0' and isnull(a.judgecnt,0) <> 0
  --判定数量为0的，都设置为配送
  update a 
  set a.cgmode = '1'
  from tmpaskdata_param a
  where a.asktype = '2' and a.cgmode = '0' and isnull(a.judgecnt,0) = 0
  --print(convert(varchar(100),getdate(),120) + '    end logic data')
  declare @saskno varchar(20)
  declare @sasktype varchar(1)
  declare cur cursor for select distinct orgcode,asktype from tmpaskdata_param order by orgcode
  open cur
  fetch next from cur into @sorgcode,@sasktype
  while @@fetch_status=0
  begin
      select @sdate=convert(varchar(10),getdate(),20),@stime = substring(convert(varchar(20),getdate(),20),12,8)
      set @saskno = ''
	  while 1=1
	  begin
		exec f_get_billno 'yh',@sorgcode,'1',@saskno output
		if exists(select 1 from t_ask_head where billno=@saskno)
		  continue
		else
		  break
	  end

	  insert into t_ask_body(billno,serialno,asktype,plucode,pluname,barcode,cargono,spec,unit,punit,itemcnt,pcount,sglcount,counts,jycounts,price,
                         jprice,netjprice,cost,netcost,jtaxrate,ypcount,depcode,depname,remark,cgmode,promdesc,sscount,ztcount,total)    
	  select @saskno,1,a.asktype,a.plucode,g.pluname,g.barcode,g.cargono,g.spec,g.unit,'' as punit,0 as itemcnt,0 as pcount,a.askcounts,a.askcounts,a.askcounts,o.price,
			 case when g.plutype='2' then 0 else o.jprice end as jprice,
			 round(case when g.plutype='2' then 0 else o.jprice/(1+isnull(g.jtaxrate,0)/100.00) end,4) as netjprice,
			 round(a.askcounts*(case when g.plutype='2' then 0 else o.jprice end),2) as cost,
			 round(a.askcounts*(case when g.plutype='2' then 0 else o.jprice/(1+isnull(g.jtaxrate,0)/100.00) end),2) as netcost,
			 g.jtaxrate,0 as ypcount,g.depcode,d.depname,'' as remark,a.cgmode,a.promdesc,a.gcount,a.onwaycount,round(a.askcounts*o.price,2)
		from tmpaskdata_param a join t_plu g on a.plucode=g.plucode
							  join t_plu_org o on a.plucode=o.plucode and a.orgcode = o.orgcode and o.orgcode=@sorgcode and o.isright='1'
							  left join t_dept d on g.depcode=d.depcode
		where a.asktype = @sasktype
	  if @@error<>0
	  begin
		set @psmsg='生成要货单明细失败'
		close cur
        deallocate cur
		return (-1)
	  end

	  select @saskbgndate = convert(varchar(10),DATEADD(dd,-1*continuedays,GETDATE()),120),
	         @saskenddate = convert(varchar(10),DATEADD(dd,continueenddays,GETDATE()),120)
	   from tmpaskdata_param 
	  where plucode = (select top 1 plucode from t_ask_body where billno = @saskno)
	    and orgcode =@sorgcode 
		and asktype = @sasktype
	  
	  insert into t_ask_head(billno,orgcode,lrdate,lrtime,depcode,depname,counts,cost,netcost,total,chkstatus,usercode,username,zdrcode,zdrname,asktype,remark,askbgndate,askenddate)
		select @saskno,upper(@sorgcode),@sdate,@stime,'','',sum(d.counts),sum(d.cost),sum(d.netcost),sum(d.total),
			   '0' as chkstatus,'0000','管理员','0000','管理员',@sasktype,'自动要货生成',@saskbgndate as askbgndate,@saskenddate as askenddate
		  from t_ask_body d 
		  where d.billno=@saskno
	  if @@error<>0 
	  begin
		set @psmsg='生成要货单主表失败'
		close cur
        deallocate cur
		return (-1)
	  end
	  insert into t_tran_log(logdate,logtime,stationid,mdlcode,mdlname,usercode,username,operation)
	  values(@sdate,@stime,'油站订货作业','','','','','生成油站订货单：'+@saskno)
	  fetch next from cur into @sorgcode,@sasktype
  end
  close cur
  deallocate cur
  --print(convert(varchar(100),getdate(),120) + '    end process data')
  set @psmsg=''
  return(1)  
end
go

if exists(select * from sysobjects where name='p_create_orderdata' and xtype='p')
  drop procedure p_create_orderdata
go
CREATE procedure p_create_orderdata
(		
  @psusercode varchar(10),			
  @pstblname varchar(100),
  @pirtn int out,
  @psmsg varchar(2000) out
)
as
  declare @sorgcode varchar(10) 
  declare @sdate varchar(10)
  declare @stime varchar(8)
  declare @susername varchar(20)
  declare @ssql varchar(8000)
  declare @icgvaliddays int
  declare @svaliddate varchar(10)
  declare @sarrivedate varchar(10)
  declare @sorderno varchar(20)
  declare @ssupcode varchar(20)
  declare @scontrno varchar(40)
begin
  set @psmsg=''
  set @pirtn = 0
  declare @sbranchno varchar(20)
  select @sbranchno = itemvalue from dbo.t_syscfg where itemname = 'branchno'
  if isnull(@sbranchno,'') = ''
  begin
    set @pirtn = -1
	set @psmsg = '未找到中央仓'
	return -1
  end

  select @susername=username from t_user where usercode = @psusercode
  ----中央仓，缺货缺省采购订单有效天数
  select @icgvaliddays=convert(int,itemvalue) from t_syscfg where section='system' and itemname='cgvaliddays'
  set @svaliddate=convert(varchar(10),dateadd(day,@icgvaliddays,getdate()),120)
  set @sarrivedate = convert(varchar(10),dateadd(day,4,getdate()),120)
  
  if exists(select * from sysobjects where name = 'tmporderdata_param' and xtype = 'U')
    drop table tmporderdata_param
  create table tmporderdata_param(
    plucode varchar(20) not null default(''),  
	billno varchar(20) not null default(''),
	orgcode varchar(10) not null default(''),  
    cgmode varchar not null default ('1'),
	clmode varchar not null default ('0'),
    supcode varchar(20) not null default(''),
	ordercnt numeric(19,4) not null default(''),
	askcounts numeric(19,4) not null default (0)
	constraint [REDACTED]primary key nonclustered
	(
		plucode,billno,orgcode
	)
  )
    ------20231108，调整根据判断数量进行调整Cgmode的方式，当要货数据大于等于判断数量(非0）为Cgmode=2，否则为Cgmode=1
   set @ssql = 'insert into tmporderdata_param(plucode,billno,orgcode,cgmode,clmode,supcode,ordercnt,askcounts) '+
              'select a.plucode,a.billno,h.orgcode,
               Case when (b.counts>=o.judgecnt And o.judgecnt >0) then ''2'' Else ''1'' end As cgmode,
               b.clmode,case when isnull(o.supcode,'''') <>'''' then o.supcode else p.supcode end as supcode,'+
              'p.ordercnt,b.counts '+
				'from '+@pstblname+' a '+
				'join  dbo.t_ask_body b on a.plucode = b.plucode and a.billno = b.billno '+
				'join dbo.t_ask_head h on a.billno = h.billno '+
				'join t_plu p on a.plucode = p.plucode '+
				'join dbo.t_plu_org o on a.plucode = o.plucode and h.orgcode = o.orgcode'
	exec (@ssql)
	if @@error <>0
	begin
	  set @pirtn = -1
	  set @psmsg = '初始数据失败'
	  return -1
	end

  update a
  set supcode =case when isnull(o.supcode,'') <> '' then o.supcode else p.supcode end
  from tmporderdata_param a,t_plu p ,t_plu_org o
  where a.plucode = p.plucode and a.plucode = o.plucode and o.orgcode = @sbranchno
    and a.cgmode = '1'

  --delete from tmporderdata_param where isnull(supcode,'') = ''
  --中央仓采购表
  if exists(select * from sysobjects where name = 'tmporderdata_cg' and xtype = 'U')
    drop table tmporderdata_cg
  create table tmporderdata_cg(
    plucode varchar(20) not null default(''),  
	supcode varchar(20) not null default(''),
	contrno varchar(40) not null default(''),
	orgcode varchar(10) not null default(''),
	ordercnt numeric(19,4) not null default 0,
	jprice numeric(19,4) not null default 0,
	counts numeric(19,4) not null default (0),
	tag varchar(1) null
	constraint pk_tmporderdata_cg primary key nonclustered
	(
		plucode,supcode,orgcode
	)
  )

  insert into tmporderdata_cg(plucode,supcode,ordercnt,orgcode, counts)
  select plucode,supcode,ordercnt,@sbranchno, sum(askcounts) as counts
  from tmporderdata_param 
  where cgmode = '1' and clmode = '0' and isnull(supcode,'') <> ''
  group by plucode,supcode,ordercnt

  /* 2023-11-08 以下内容不用这么复杂的控制
  if exists(select * from sysobjects where name = 'tmporderdata_onway' and xtype = 'U')
    drop table tmporderdata_onway
  create table tmporderdata_onway(
    plucode varchar(20) not null default(''),  
	askcount numeric(19,4) not null default 0,
	onwaycount numeric(19,4) not null default (0)
	constraint [REDACTED]primary key nonclustered
	(
		plucode
	)
  )

  insert into tmporderdata_onway(plucode,askcount,onwaycount)
  select a.plucode,askcounts,onwaycount
  from
	  (select plucode,sum(askcounts) as askcounts,sum(onwaycount) as onwaycount
	  from (
	       /* 2023-11-08，物流已处理的状态订货数据，已经生成了采购订单了
		  select plucode,sum(b.counts) as askcounts, 0 as onwaycount from t_ask_body b,t_ask_head h
		  where b.billno = h.billno and isnull(h.rzdate,'') <> '' and b.clstate = '1' and b.clmode = '0' and b.cgmode = '1'
		  group by b.plucode
		  union all
		  */
	      -----只统计中央仓的采购订单执行状态的在途库存数据
		  select plucode,0 as askcounts, sum(b.counts-b.dhcount)as onwaycount from t_order_body b,t_order_head h,dbo.t_shop s
		  where b.billno = h.billno and h.orgcode = s.orgcode and s.orgtype = '2' 
			and h.state = '1'
		  group by b.plucode
	  )src1
	  group by plucode
	  )a,tmporderdata_cg b where a.plucode = b.plucode

  --中央仓采购订单
	  -----处理冲减中央仓已有的库存数据和执行中的采购订单未到货库存数量
 
 update a
  set a.counts = a.counts + b.askcount - b.onwaycount - isnull(o.gcount,0) - isnull(o.ccount,0)
  from tmporderdata_cg a  join tmporderdata_onway b on a.plucode = b.plucode 
       join t_plu_org o on a.plucode = o.plucode and o.orgcode = @sbranchno

     *2023-11-08 以上内容不用这么复杂的控制
     *  ----按中央仓库存+中央仓采购订单执行状态且未收完货的数据
        Select pluCode ,sum(onwaycount)  as onwaycount From 
      	     (Select pluCode,(isnull(gcount,0)+isnull(ccount,0)) as onwaycount from t_plu_org where orgcode='c001'
		       union all
		       select plucode, sum(b.counts-b.dhcount) as onwaycount from t_order_body b,t_order_head h,dbo.t_shop s
				  where b.billno = h.billno and h.orgcode = s.orgcode and s.orgcode='c001'
					and h.state = '1'
				  group by b.plucode ) TT group by plucode  
     */
	  
  ---------20231108按中央仓库存+中央仓采购订单执行状态且未收完货的数据 ---20231109 在途库存需要减去物流已处理 中央仓未处理的配送要货单数量
    update a
  set a.counts = a.counts -o.onwaycount
  from tmporderdata_cg a  
     join ( Select pluCode ,sum(onwaycount)  as onwaycount From 
           (Select pluCode,(isnull(gcount,0)+isnull(ccount,0)) as onwaycount from t_plu_org where orgcode= @sbranchno
	         union all
	        select plucode, sum(b.counts-b.dhcount) as onwaycount from t_order_body b,t_order_head h,dbo.t_shop s
			 where b.billno = h.billno and h.orgcode = s.orgcode and s.orgcode= @sbranchno
			   and h.state = '1'
			 group by b.plucode 
			 union all 
			select pluCode ,-sum(c.counts) as onwaycount from t_ask_body c , t_ask_head tah  where c.cgmode='1' and clstate = '1' and c.billno = tah.billno  and tah.state ='0' 
			 group by c.plucode
			  ) TT group by plucode ) o on a.plucode = o.plucode  
       
  update a
  set 
      counts = case ordercnt when 0 then counts else round(counts/ordercnt,0)*ordercnt end,
      contrno = isnull((select top 1 c.contrno 
						from t_contract c , t_contr_org co
						where c.contrno = co.contrno and supcode = a.supcode and co.orgcode = a.orgcode and contrstatus = '0' 
						  and CONVERT(varchar(10),GETDATE(),120) between bgndate and enddate
						order by signdate,c.contrno)
						,'')
  from tmporderdata_cg a
  where counts > 0

  
  --获取进价
  update a
  set jprice = case when isnull(sp.jymode,'') = '2' then 0 
               else case when Exists (select JPrice from t_order_quote H  where H.QuoteType='1' and convert(varchar(10),getdate(),120) between BgnDate and EndDate
			                           and h.orgcode = a.orgcode and h.plucode = a.plucode and h.supcode = a.supcode)
				        then (select top 1 JPrice from  t_order_quote H,(select QuoteType,OrgCode,supcode,PluCode,max(RzDate+' '+RzTime) RzDateTime from t_order_quote where QuoteType='1'  and convert(varchar(10),getdate(),120) between BgnDate and EndDate group by QuoteType,OrgCode,supcode,PluCode) B 
							where H.QuoteType=B.QuoteType and H.OrgCode=B.OrgCode and H.supcode=B.supcode and H.PluCode=B.PluCode and H.RzDate+' '+H.RzTime=B.RzDateTime
							and convert(varchar(10),getdate(),120) between BgnDate and EndDate 
							and h.orgcode = a.orgcode and h.plucode = a.plucode and h.supcode = a.supcode)
						--when Exists (select JPrice from t_order_quote H where H.QuoteType='0' and h.orgcode = a.orgcode and h.plucode = a.plucode and h.supcode = a.supcode)
						--then (select JPrice from t_order_quote H where H.QuoteType='0' and h.orgcode = a.orgcode and h.plucode = a.plucode and h.supcode = a.supcode)
						else o.ojprice end end,
	 tag = case when isnull(sp.jymode,'') = '2' then '0'
	       else case when Exists (select JPrice from  t_order_quote H where H.QuoteType='1' and convert(varchar(10),getdate(),120) between BgnDate and EndDate 
		                           and h.orgcode = a.orgcode and h.plucode = a.plucode and h.supcode = a.supcode) then '1'
                     --when Exists( select JPrice from t_order_quote H where H.QuoteType='0' and h.orgcode = a.orgcode and h.plucode = a.plucode and h.supcode = a.supcode) then '1'
					 else '0' end
		  end
	 
  from tmporderdata_cg a,t_plu_org o,t_supplier sp, t_plu g
  where a.plucode = o.plucode and o.orgcode = a.orgcode and a.supcode = sp.supcode and a.plucode = g.plucode

  
 -- 	update a
	--set cgdate=@sdate,clstate = '1'
	--from t_ask_body a,tmporderdata_param b 
	--where a.billno = b.billno and a.plucode = b.plucode and a.cgmode = '1' 
	  --and exists (select * from tmporderdata_cg where plucode = b.plucode and counts <= 0)

  declare cur cursor for select distinct supcode,orgcode,contrno from tmporderdata_cg where counts > 0 and contrno <> '' order by supcode
  open cur
  fetch next from cur into @ssupcode,@sorgcode,@scontrno
  while @@fetch_status = 0
  begin
      select @sdate=convert(varchar(10),getdate(),20),@stime = substring(convert(varchar(20),getdate(),20),12,8)
	  
      set @sorderno = ''
	  while 1=1
	  begin
		exec f_get_billno 'CG',@sorgcode,'1',@sorderno output
		if exists(select 1 from t_order_head where billno=@sorderno)
		  continue
		else
		  break
	  end
    print (@sorderno)
	insert into t_order_body(billno,serialno,plucode,pluname,barcode,cargono,spec,unit,price,counts,
                           jprice,netjprice,ornjprice,ornnetjprice,cost,netcost,jtaxrate,depcode,depname,remark,pcount,punit,itemcnt,sglcount,tag)
    select @sorderno,0 as serialno,a.plucode,g.pluname,g.barcode,g.cargono,g.spec,g.unit,o.price,a.counts,
           a.jprice,round(a.jprice/(1+isnull(g.jtaxrate,0)/100.00),4) as netjprice,a.jprice,round(a.jprice/(1+isnull(g.jtaxrate,0)/100.00),4) as ornnetjprice,
           round(a.counts*a.jprice,2) as cost,
           round(round(a.counts*a.jprice,2)/(1+isnull(g.jtaxrate,0)/100.00),2) as netcost,
           g.jtaxrate,g.depcode,d.depname,'' as remark,
		   case when isnull(a.ordercnt,0)=0 then 0 else round(a.counts/a.ordercnt,1) end as pcount,
		   '' as punit,a.ordercnt as itemcnt,a.counts as sglcount,a.tag
     from tmporderdata_cg a join t_plu g on a.plucode=g.plucode
          join t_plu_org o on a.plucode=o.plucode and a.orgcode = o.orgcode and o.orgcode=@sbranchno 
		  left join t_dept d on g.depcode = d.depcode
	where  a.supcode = @ssupcode and a.counts > 0 and a.contrno <> '' 

	  if @@error<>0
	  begin
		set @psmsg='生成中央仓订单明细失败'
	    close cur
        deallocate cur
		set @pirtn = -1
		return (-1)
	  end
	  
	  insert into t_order_head(billno,orgcode,billtype,bizdate,lrdate,lrtime,
							   counts,cost,netcost,zdrcode,zdrname,usercode,username,
							   chkstatus,remark,sqauremode,supcode,supname, depcode,depname,contrno,arrivedate,paydate,validdate,iszs)
		select @sorderno,upper(@sorgcode),'0',@sdate,@sdate,@stime,
			   sum(d.counts),sum(d.cost),sum(d.netcost), @psusercode,@susername,@psusercode,@susername,
			   '0' as chkstatus,'油站订货处理生成','1' as sqauremode,@ssupcode,(select supname from t_supplier where supcode = @ssupcode) as supname,
			   '' as depcode,'' as depname,@scontrno as contrno,@sarrivedate,@svaliddate,@svaliddate,'0'
		  from t_order_body d where d.billno=@sorderno  
	  if @@error<>0 
	  begin
		set @pirtn = -1
		set @psmsg='生成中央仓订单主表信息失败' 
		close cur
        deallocate cur 
		return (-1)
	  end

	  --更新处理状态
	  --update a
	  --set cgdate=@sdate,clstate = '1'
	  --from t_ask_body a,tmporderdata_param b 
	  --where a.billno = b.billno and a.plucode = b.plucode and a.cgmode = '1' and b.supcode = @ssupcode

	  --update t_order_head
	  --set state = '1',
	  --    rzdate = @sdate,rztime = @stime
	  --where billno = @sorderno
	  
	  insert into t_tran_log(logdate,logtime,stationid,mdlcode,mdlname,usercode,username,operation)
	  values(@sdate,@stime,'','','油站订货处理',@psusercode,@susername,'油站订货处理生成：'+@sorderno)
	  fetch next from cur into @ssupcode,@sorgcode,@scontrno
  end
  close cur
  deallocate cur


  --处理直送单
  truncate table tmporderdata_cg

  insert into tmporderdata_cg(plucode,supcode,ordercnt,orgcode, counts)
  select plucode,supcode,ordercnt,orgcode, sum(askcounts) as counts
  from tmporderdata_param 
  where cgmode = '2' and clmode = '0' and isnull(supcode,'') <> ''
  group by plucode,supcode,ordercnt,orgcode

  update a
  set counts = case ordercnt when 0 then counts else round(counts/ordercnt,0)*ordercnt end,
      contrno = isnull((select top 1 c.contrno 
						from t_contract c , t_contr_org co
						where c.contrno = co.contrno and supcode = a.supcode and co.orgcode = a.orgcode and contrstatus = '0' 
						  and CONVERT(varchar(10),GETDATE(),120) between bgndate and enddate
						order by signdate,c.contrno)
						,'')
  from tmporderdata_cg a
					
  where counts > 0
  --获取进价
  update a
  set jprice = case when isnull(sp.jymode,'') = '2' then 0 
               else case when Exists (select JPrice from t_order_quote H  where H.QuoteType='1' and convert(varchar(10),getdate(),120) between BgnDate and EndDate
			                           and h.orgcode = a.orgcode and h.plucode = a.plucode and h.supcode = a.supcode)
				        then (select top 1 JPrice from  t_order_quote H,(select QuoteType,OrgCode,supcode,PluCode,max(RzDate+' '+RzTime) RzDateTime from t_order_quote where QuoteType='1'  and convert(varchar(10),getdate(),120) between BgnDate and EndDate group by QuoteType,OrgCode,supcode,PluCode) B 
							where H.QuoteType=B.QuoteType and H.OrgCode=B.OrgCode and H.supcode=B.supcode and H.PluCode=B.PluCode and H.RzDate+' '+H.RzTime=B.RzDateTime
							and convert(varchar(10),getdate(),120) between BgnDate and EndDate 
							and h.orgcode = a.orgcode and h.plucode = a.plucode and h.supcode = a.supcode)
						--when Exists (select JPrice from t_order_quote H where H.QuoteType='0' and h.orgcode = a.orgcode and h.plucode = a.plucode and h.supcode = a.supcode)
						--then (select JPrice from t_order_quote H where H.QuoteType='0' and h.orgcode = a.orgcode and h.plucode = a.plucode and h.supcode = a.supcode)
						else o.ojprice end end,
	 tag = case when isnull(sp.jymode,'') = '2' then '0'
	       else case when Exists (select JPrice from  t_order_quote H where H.QuoteType='1' and convert(varchar(10),getdate(),120) between BgnDate and EndDate 
		                           and h.orgcode = a.orgcode and h.plucode = a.plucode and h.supcode = a.supcode) then '1'
                     --when Exists( select JPrice from t_order_quote H where H.QuoteType='0' and h.orgcode = a.orgcode and h.plucode = a.plucode and h.supcode = a.supcode) then '1'
					 else '0' end
		  end
	 
  from tmporderdata_cg a,t_plu_org o,t_supplier sp, t_plu g
  where a.plucode = o.plucode and o.orgcode = a.orgcode and a.supcode = sp.supcode and a.plucode = g.plucode

  --update a
  --set cgdate=@sdate,clstate = '1'
  --from t_ask_body a,tmporderdata_param b 
  --where a.billno = b.billno and a.plucode = b.plucode and a.cgmode = '2' 

  declare curZ cursor for select distinct supcode,orgcode,contrno  from tmporderdata_cg where counts > 0 and contrno <> '' order by orgcode,supcode
  open curZ
fetch next from curZ into @ssupcode,@sorgcode,@scontrno
  while @@fetch_status = 0
  begin
      select @sdate=convert(varchar(10),getdate(),20),@stime = substring(convert(varchar(20),getdate(),20),12,8)
      set @sorderno = ''
	  while 1=1
	  begin
		exec f_get_billno 'ZCG',@sorgcode,'1',@sorderno output
		if exists(select 1 from t_order_head where billno=@sorderno)
		  continue
		else
		  break
	  end

	insert into t_order_body(billno,serialno,plucode,pluname,barcode,cargono,spec,unit,price,counts,
                           jprice,netjprice,ornjprice,ornnetjprice,cost,netcost,jtaxrate,depcode,depname,remark,pcount,punit,itemcnt,sglcount,tag)
    select @sorderno,0 as serialno,a.plucode,g.pluname,g.barcode,g.cargono,g.spec,g.unit,o.price,a.counts,
           a.jprice,round(a.jprice/(1+isnull(g.jtaxrate,0)/100.00),4) as netjprice,a.jprice,round(a.jprice/(1+isnull(g.jtaxrate,0)/100.00),4) as ornnetjprice,
           round(a.counts*a.jprice,2) as cost,
           round(round(a.counts*a.jprice,2)/(1+isnull(g.jtaxrate,0)/100.00),2) as netcost,
           g.jtaxrate,g.depcode,d.depname,'' as remark,
		   case when isnull(a.ordercnt,0)=0 then 0 else round(a.counts/a.ordercnt,1) end as pcount,
		   '' as punit,a.ordercnt as itemcnt,a.counts as sglcount,a.tag
     from tmporderdata_cg a join t_plu g on a.plucode=g.plucode
          join t_plu_org o on a.plucode=o.plucode and a.orgcode = o.orgcode and o.orgcode=@sorgcode 
		  left join t_dept d on g.depcode = d.depcode
	where  a.supcode = @ssupcode and a.counts > 0 and a.contrno <> ''

	  if @@error<>0
	  begin
		set @psmsg='生成油站直送订单明细失败'
		set @pirtn = -1
		close curZ
        deallocate curZ
		return (-1)
	  end
	  
	  insert into t_order_head(billno,orgcode,billtype,bizdate,lrdate,lrtime,
							   counts,cost,netcost,zdrcode,zdrname,usercode,username,
							   chkstatus,remark,sqauremode,supcode,supname,depcode,depname,contrno,arrivedate,paydate,validdate,iszs)
		select @sorderno,upper(@sorgcode),'0',@sdate,@sdate,@stime,
			   sum(d.counts),sum(d.cost),sum(d.netcost), @psusercode,@susername,@psusercode,@susername,
			   '0' as chkstatus,'油站订货处理生成','1' as sqauremode,@ssupcode,(select supname from t_supplier where supcode = @ssupcode) as supname,
			   '' as depcode,'' as depname,@scontrno as contrno,@sarrivedate,@svaliddate,@svaliddate,'1'
		  from t_order_body d where d.billno=@sorderno  
	  if @@error<>0 
	  begin
		set @pirtn = -1
		set @psmsg='生成油站直送订单主表信息失败'  
		close curZ
        deallocate curZ
		return (-1)
	  end

	  --更新处理状态
	  --update a
	  --set cgdate=@sdate,clstate = '1'
	  --from t_ask_body a,tmporderdata_param b 
	  --where a.billno = b.billno and a.plucode = b.plucode and a.cgmode = '2' and b.supcode = @ssupcode and b.orgcode = @sorgcode

	  --update t_order_head
	  --set state = '1',
	  --    rzdate = @sdate,rztime = @stime
	  --where billno = @sorderno
	  
	  insert into t_tran_log(logdate,logtime,stationid,mdlcode,mdlname,usercode,username,operation)
	  values(@sdate,@stime,'','','油站订货处理',@psusercode,@susername,'油站订货处理生成：'+@sorderno)
	  fetch next from curZ into @ssupcode,@sorgcode,@scontrno
  end
  close curZ
  deallocate curZ

  update a
     set cgdate=@sdate,clstate = '1'
    from t_ask_body a,tmporderdata_param b 
   where a.billno = b.billno and a.plucode = b.plucode
 if @@error<>0 
 begin
   set @pirtn = -1
   set @psmsg='更新油站订单处理状态失败'  
   return (-1)
 end
  set @psmsg=''
  return(1)  
end
go