IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_customer_newcst]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_customer_newcst]
GO


-- 生成时间:2018-04-13 11:31:44 by ebs-core  
CREATE  procedure mps_customer_newcst(
     @cmpid int, 
     @branchid int, 
     @userdpid int, 
     @userotid int, 
     @useruid int, 
     @ctid int,
     @returndatasets int ,  
     @extparam1 nvarchar(1000),
     @extparam2 nvarchar(1000),
     @extparam3 nvarchar(1000),
     @newccid bigint output  
  ) 
  as  
  begin  
  set nocount on  
  
 
  if ((@extparam1 is null) or (@extparam1='_none_'))  set @extparam1 = '' 
  if ((@extparam2 is null) or (@extparam2='_none_'))  set @extparam2 = '' 
  if ((@extparam3 is null) or (@extparam3='_none_'))  set @extparam3 = '' 
  
  
  set @newccid = 0  
  
  declare @bizcode nvarchar(100)    
  select   @bizcode=ct_bmcode  from mps_csttype where  ct_id=@ctid    
  declare @ccno varchar(50)     
select top 1 @newccid=cc_id from mps_customer where cc_cmpid=@cmpid and cc_ctid=@ctid and cc_createcuid=@useruid and cc_code like '%临%'  
  set @newccid = ISNULL(@newccid,0) 
  if (@newccid>0) 
  begin
update mps_customer set cc_createtime = GETDATE() , cc_updated = GETDATE() where cc_id=@newccid 
  end else 
  begin
  insert into mps_customer(cc_cmpid,cc_bcid,cc_branch,cc_dpid,cc_depart,cc_cuid,cc_cuname,cc_tag,cc_caption,cc_ctid,cc_type,cc_name,
  cc_createdpid,cc_createdepart,cc_createcuid,cc_creator,cc_createtime,cc_updated) 
  select @cmpid,bc_id,bc_company,dp_id,dp_depart,cu_id,cu_callname,ct_tag,ct_caption,ct_id,ct_type, 'new',
  dp_id,dp_depart,cu_id,cu_callname,getdate(),getdate() 
from mps_csttype,mps_login,mps_depart,mps_groupbranch 
where ct_id=@ctid and cu_id=@useruid and dp_id=@userdpid and bc_id=@branchid  and bc_cmpid=@cmpid  
select top 1 @newccid = cc_id from mps_customer where cc_cmpid=@cmpid and cc_ctid=@ctid and cc_createcuid=@useruid and cc_name='new' order by cc_id desc  
  
set @newccid = isnull(@newccid,0) 
-- 生成订单编号（临时） 
exec mps_bm_getorset @cmpid,'cst',@ctid,@newccid,@useruid,@bizcode,2,@ccno output,1   
update mps_customer set cc_code = @ccno where cc_id = @newccid   
   
  -- why here otid=-1 , it's a secret , I don't know yet 
  insert into mps_customer_users(ccp_type,ccp_ccid,ccp_cuid,ccp_otid) 
  select distinct 'cstview',@newccid,@useruid,-1  
  insert into mps_customer_users(ccp_type,ccp_ccid,ccp_cuid,ccp_otid) 
  select distinct 'cstedit',@newccid,@useruid,-1  
  end 
   
  -- 返回客户数据  

  if (@returndatasets=0) select * from  mps_customer where cc_id=@newccid 
  if (@returndatasets=2) select @newccid newccid   
  set nocount off  
end