

create PROCEDURE [dbo].[EShop_FactorInsert]
    @Number NUMERIC(18, 0) OUTPUT ,
    @CustomerId UNIQUEIDENTIFIER ,
    @WearhouseGoodsId UNIQUEIDENTIFIER ,
    @TotalFactorPrice MONEY ,
    @Note NTEXT = NULL ,
    @GUID UNIQUEIDENTIFIER,
    @Date DATE ,

	@NumberOrder int,
	@Name Nvarchar(max),
	@Mobile Varchar(20),
	@Addr Nvarchar(Max),
	@Email Varchar(50),
	@PostalCode Varchar(20),
	@Position varchar(50), 
	@OrderId uniqueidentifier,
    @DeliveryFamily nvarchar(100),
    @OrderDate DateTime,     
    @DeliveryMoBile varchar(11),
    @DeliVeryAddr nvarchar(150),
    @Description nvarchar(150),
    @DelivaryDate varchar(50)

AS
   
	Begin Try
	Begin Tran

	--DEclare @OrderDateMiladi datetime = dbo.ShamsiToMiladi(@orderdate)
	DECLARE @Receiver NVARCHAR(35) ,
            @Sender NVARCHAR(35),
			@Guycode varchar(5)


	Set @Sender = N'انبار فروش'
	set @Receiver = N'خريداران اينترنتي'

	set @guyCode = '10000'
    SELECT @Receiver = Name, @Guycode = Guy_Code
    FROM   dbo.Guy
    WHERE  mobile = @Mobile

	Declare @clubId int = (Select Autoid From Tbl_ClubH Where Mobile = @Mobile)
	if IsNull(@clubId,0) = 0
	begin
	  Insert into Tbl_ClubH(Name, Addr, Mobile,Email, PostalCode, Position) Values(@Name,@Addr, @Mobile, @Email, @PostalCode, @Position)
	  set @clubId = SCOPE_IDENTITY()
	end
	else
	  Update Tbl_ClubH set Name = @Name, Addr = @Addr, 
	  Position = @Position, Email =  @Email, PostalCode = @PostalCode Where AutoId = @clubId
     
    INSERT INTO [TmpHeadH] ( [Kind_Flag] ,
	                         [Nu_Havaleh] ,
                             [Recive_Name] ,
                             [Trans_Name] ,
                             [Tot_Price_KHarid] ,
                             [Tot_Price_forosh] ,
                             [Tot_Price_Omdeh] ,
                             [Tarikh_faktor] ,
                             [Note] ,
                             [Tot_Kahandeh] ,
                             [Tot_Afzayandeh] ,
                             [kind_Save] ,
                             [User_id] ,
                             [Id] ,
							 [Items],
							 [Number_bar],
							 [ClubId]
							 )
    VALUES ( 7, @NumberOrder, @Receiver, @Sender, 0, @TotalFactorPrice, 0, @Date, @Note, 0, 0, 2, 0, @GUID,-1,1, @clubId)
    DECLARE @id bigint = scope_identity()
   
   insert into TrackingHeader (Id,NuOrder,Family,OrderDate,Mobile,Address,Description,DeliveryDate)
   values ( @OrderId,@NumberOrder,@DeliveryFamily,@OrderDate,@DeliveryMoBile,@DeliVeryAddr,@Description,@DelivaryDate)
   --TrackingDetail
   insert into TrackingDetail(TrackingHeaderId,TrackingDate,Status,IsDone)
   values 
   (@OrderId,getdate(),0,1),
   (@OrderId,NULL,1,0),
   (@OrderId,NULL,2,0),
   (@OrderId,NULL,3,0),
   (@OrderId,NULL,4,0),
   (@OrderId,NULL,8,0),
   (@OrderId,NULL,9,0)
	Commit Tran
    RETURN @id
	
	End Try
	Begin Catch
	  RollBack Tran
	  set @Id = -1
	  return @id
	End Catch



