CREATE FUNCTION  [dbo].[CycleAvgAnbar]  (@ACode Char(3),  @KCode Varchar(20),  @Date1 smalldatetime,@Date2 smalldatetime  , @FlagSearch Char(1), @TypeCalcPrice Char(1))
RETURNS
@CycleAnbar TABLE
   (
   ACode   Varchar(3),
   K_Code  varchar(15),
   Name1 Nvarchar(50),
   QtyKharid  Float, 
   QtyBForosh Float , 
   QtyTVorod Float, 
   QtyForosh Float ,  
   QtyBKharid Float ,  
   QtyTSodor Float , 
   SumKharid Money, 
   SumBForosh Money,  
   PriceTVorod Money,       
   SumForosh Money ,  
   PriceTSodor Money,
   SumBKharid Money,  
   Vorod  float,
   Sodor float,
   EnterPrice Money,
   ExitPrice Money,
   Mandeh float,
   PriceMin Money
   )
AS  
BEGIN 
  IF @FlagSearch = '1' 
  BEGIN
     INSERT @CycleAnbar
     Select @Acode ACode , K_Code, Name1, 
      Sum(QtyKharid) QtyKharid,Sum(QtyBForosh) QtyBForosh, Sum(QtyTVorod)  QtyTVorod,
      Sum(QtyForosh) QtyForosh,Sum(QtyBKharid) QtyBKharid , Sum(QtyTSodor) QtyTSodor, 
      Sum(SumKharid) SumKharid,Sum(SumBForosh) SumBForosh, Sum(PriceTVorod) PriceTVorod,
      Sum(SumForosh) SumForosh,Sum(PriceTSodor)PriceTSodor,Sum(SumBKharid) SumBKharid,          
      Sum(Vorod) Vorod , Sum(Sodor) Sodor , Sum(EnterPrice) EnterPrice, 
      Sum(ExitPrice) ExitPrice , Sum(Vorod) - Sum(Sodor) Mandeh  ,
      Sum(EnterPrice) - Sum(ExitPrice)  PriceMin  From (
      Select K_Code, Name1, 
      Sum(QtyKharid) QtyKharid,Sum(QtyBForosh) QtyBForosh, Sum(QtyTVorod)  QtyTVorod,
      Sum(QtyForosh) QtyForosh,Sum(QtyBKharid) QtyBKharid ,Sum(QtyTSodor) QtyTSodor, 
      Sum(SumKharid) SumKharid,Sum(SumBForosh) SumBForosh, Sum(PriceTVorod) PriceTVorod,
      Sum(SumForosh) SumForosh,Sum(PriceTSodor)PriceTSodor,Sum(SumBKharid) SumBKharid,          
      Sum(Vorod) Vorod , Sum(Sodor) Sodor , Sum(EnterPrice) EnterPrice, Sum(ExitPrice) ExitPrice
      From (
             SELECT Kalaid.K_Code,Kind_Flag,Name1,
			 ------------------------------------------------------------------(Enter Detail)-------------------------------------
			 Sum(Case When Reciver = @ACode And Kind_Flag in (2,3)   Then  K_Qty1 Else 0  End) As QtyKharid ,
			 Sum(Case When Reciver = @ACode And Kind_Flag in (0,6,8) Then  K_Qty1 Else 0  End) As QtyBForosh,
			 Sum(Case When Reciver = @ACode And Kind_Flag = 1        Then  K_Qty1 Else 0  End) As QtyTVorod,
			 ------------------------------------------------------------------(Exit Detail)-------------------------------------
			 Sum(Case When Sender = @ACode  And Kind_Flag in (5,7,9) Then K_Qty1 Else 0  End ) As QtyForosh,
			 Sum(Case When Sender = @ACode  And Kind_Flag  =  4      Then K_Qty1 Else 0  End ) As QtyBKharid,
			 Sum(Case When Sender = @ACode  And Kind_Flag  =  1      Then K_Qty1 Else 0  End ) As QtyTSodor,
             
			 ------------------------------------------------------------------(Enter Price Detail )-------------------------------------
			 Sum(Case When Reciver = @ACode And Kind_Flag  in (2,3) Then Price_Kharid * K_Qty1 Else 0 End 
			     ) As SumKharid,
			 
			 Sum(
			      Case  
			        When Reciver = @ACode And @TypeCalcPrice = 'K' And Kind_Flag  in (0,6,8) Then Price_Kharid * K_Qty1 
			        When Reciver = @ACode And @TypeCalcPrice = 'M' And Kind_Flag  in (0,6,8) Then Round(Avg_Price,0) * K_Qty1 
			      Else 0 End)   As SumBForosh,
			 
			 Sum(Case  When Reciver = @ACode  And Kind_Flag  = 1   Then Round(Avg_Price,0) * K_Qty1 Else 0 End) As PriceTVorod,
			 ------------------------------------------------------------------(Exit Price Detail )--------------------------------------
			 Sum(Case   
			       When Sender =  @ACode And @TypeCalcPrice = 'K'  And Kind_Flag in (5,7,9)  Then Price_Forosh * K_Qty1 
			       When Sender =  @ACode And @TypeCalcPrice = 'M'  And Kind_Flag in (5,7,9)  Then Round(Avg_Price,0) * K_Qty1 
			       Else 0  End)      
			     As SumForosh,
			 Sum(Case   When Sender =  @ACode   And Kind_Flag   = 1 Then Round(Avg_Price,0) * K_Qty1 Else 0 End) As PriceTSodor,
			 Sum(Case   
			       When Sender =  @ACode And @TypeCalcPrice = 'K'  And Kind_Flag   = 4  Then Price_Kharid * K_Qty1 
			       When Sender =  @ACode And @TypeCalcPrice = 'M'  And Kind_Flag   = 4  Then Round(Avg_Price,0) * K_Qty1 
			       Else 0 End
			     )       
			      As SumBKharid,
			 -----------------------------------------------------------------------------------------------------------------------------
             Case
               When Sender  = @ACode   then  '1'
               When Reciver = @ACode   then  '2'
             End As Type,
             Sum(Case When Reciver = @ACode Then K_Qty1 Else 0 End) As Vorod,
             Sum(Case When Sender = @ACode Then K_Qty1 Else 0 End) As Sodor,
             Sum(Case
                  when Reciver = @ACode And headH.Kind_Flag in (2,3) Then Price_KHarid* K_Qty1 
                  when Reciver = @ACode And headH.Kind_Flag in (1)   Then Avg_Price* Havaleh.K_Qty1
                  when Kind_Flag in (0,6,8)                          Then Avg_Price* K_Qty1   
                  Else 0 
                 End) As EnterPrice,
             Sum(Case
                    When HeadH.kind_flag in (4,5,7,9)  Then Avg_Price * K_Qty1
                    When Sender = @ACode And kind_flag = 1  Then Avg_Price * K_Qty1
                    Else 0 
             End) As ExitPrice

     FROM  headH INNER JOIN Havaleh ON headH.Id_Havaleh = Havaleh.Id_Havaleh
     Inner Join Kalaid On (Havaleh.K_Code = Kalaid.K_Code)
     Where Convert(Varchar(10), Tarikh_Faktor, 111) >= @Date1
     And Convert(Varchar(10), Tarikh_Faktor, 111) <= @Date2
     And (Sender =  @ACode or Reciver = @ACode)
     Group By Kalaid.K_Code, Sender, Reciver, Kind_Flag,Name1
    ) As T1
     Group By Type, K_Code,Name1) as T1
     Group By K_Code,Name1
  END
  ElSE IF @FlagSearch = '2' 
  BEGIN
        INSERT @CycleAnbar
        Select T.A_Code, T.K_Code, Name1, 
        QtyKharid,QtyBForosh, QtyTVorod,
        QtyForosh,QtyBKharid ,QtyTSodor, 
        SumKharid,SumBForosh, PriceTVorod,
        SumForosh,PriceTSodor,SumBKharid,          
        T1.vorod ,T1.Sodor ,EnterPrice , ExitPrice ,
        T1.vorod - T1.Sodor Mandeh , PriceMin From (
        
        Select T3.A_Code, T3.K_Code, T3.Name1, 
        0 QtyKharid,0 QtyBForosh, 0  QtyTVorod,
        0 QtyForosh,0 QtyBKharid ,0 QtyTSodor, 
        0 SumKharid,0 SumBForosh, 0 PriceTVorod,
        0 SumForosh,0 PriceTSodor,0 SumBKharid,          
        0 vorod ,0 Sodor ,0 EnterPrice , 0 ExitPrice ,
        0 Mandeh , T3.Avg_Price PriceMin  From (
        SELECT  Havaleh.K_Code, Havaleh.AutoId,
        headH.Tarikh_faktor, SUM(Havaleh.K_Qty1) 
        AS SumKQty, KalaId.Name1, HeadH.Kind_Flag,
        Case  
		   when kind_flag=2 then 1
		   when kind_flag=3 then 2    
		   when kind_flag=6 then 3    
		   when kind_flag=8 then 4    
		   when kind_flag=0 then 5    
		   when kind_flag=1 then 6    
		   when kind_flag=4 then 7    
		   when kind_flag=5 then 8    
		   when kind_flag=7 then 9    
		   when kind_flag=9 then 10   
        End as Radif,
       Case
          When Sender  <> @ACode Then Reciver
          When Reciver <> @ACode Then Sender
        End As A_Code,
       Case
          When Reciver = @ACode And Kind_Flag = '1' then Tot_Omdeh
          else
            Avg_Price
        End As Avg_Price 
        FROM headH INNER JOIN
         Havaleh ON headH.Id_Havaleh = Havaleh.Id_Havaleh INNER JOIN
         Anbar ON Havaleh.K_Code = Anbar.K_Code INNER JOIN
         KalaId ON Anbar.K_Code = KalaId.K_Code
         WHERE (Sender = @ACode Or Reciver = @ACode)
         And Convert(Varchar(10), Tarikh_Faktor, 111) >= @Date1
         And Convert(Varchar(10), Tarikh_Faktor, 111) <= @Date2
         And Havaleh.K_Code  = (Case When @Kcode = '' then Havaleh.K_Code  Else @Kcode end)
         GROUP BY Havaleh.K_Code, Havaleh.Tot_Omdeh,
         headH.Tarikh_faktor, Havaleh.Avg_Price,KalaId.Name1,Havaleh.Sender, Havaleh.Reciver,  
         HeadH.Kind_Flag, Havaleh.AutoId) As T3
         Inner Join 
           (
             ------------------------------------------------------------
	 Select MaxTarikh, K_Code, Max(Radif) Radif,Max(AutoId) Autoid From (
	 Select T1.MaxTarikh, T.K_Code, T.Radif ,AutoId  From 
	 (
	    SELECT MAX(Tarikh_Faktor) MaxTarikh, K_code
	    FROM HeadH INNER JOIN Havaleh ON HeadH.Id_Havaleh = Havaleh.Id_Havaleh
        Where Convert(Varchar(10), Tarikh_Faktor, 111) >= @Date1
        And Convert(Varchar(10), Tarikh_Faktor, 111) <= @Date2
        And Havaleh.K_Code  = (Case When @Kcode = '' then Havaleh.K_Code  Else @Kcode end)
	     And (Sender = @ACode Or Reciver = @ACode)
	     GROUP BY K_code) As T1
	     Inner Join 
	    ( 
	      SELECT K_code,Tarikh_Faktor,Havaleh.AutoId,
	      Case  
		   when kind_flag=2 then 1
		   when kind_flag=3 then 2    
		   when kind_flag=6 then 3    
		   when kind_flag=8 then 4    
		   when kind_flag=0 then 5    
		   when kind_flag=1 then 6    
		   when kind_flag=4 then 7    
		   when kind_flag=5 then 8    
		   when kind_flag=7 then 9    
		   when kind_flag=9 then 10   
	      End as RadiF  
	      FROM HeadH INNER JOIN Havaleh ON HeadH.Id_Havaleh = Havaleh.Id_Havaleh
          Where Convert(Varchar(10), Tarikh_Faktor, 111) >= @Date1
          And Convert(Varchar(10), Tarikh_Faktor, 111) <= @Date2
	      And (Sender = @ACode Or Reciver = @ACode)
          And Havaleh.K_Code  = (Case When @Kcode = '' then Havaleh.K_Code  Else @Kcode end)
	      GROUP BY K_code, kind_flag,Tarikh_Faktor,Havaleh.AutoId) As T
	      On (T.K_Code = T1.K_Code And T.Tarikh_Faktor = T1.MaxTarikh)) As T5
	      Group By K_Code, MaxTarikh
                    ) As T4
                    On (T3.K_Code = T4.K_Code And T3.Tarikh_faktor = T4.MaxTarikh And T3.AutoId = T4.AutoId)
                   Group By T3.A_Code, T3.K_Code, T3.Name1, T3.Avg_Price 
     ) As T 
     Inner Join 
     (                  

        Select @ACode A_Code, K_code , Sum(Vorod) Vorod , Sum(Sodor) Sodor From (
        Select K_Code, 
        Sum(Case When Reciver =@ACode Then K_Qty1 Else 0 End) As Vorod,
        SUm(Case When Sender =@ACode Then K_Qty1 Else 0 End)  As Sodor
        From Havaleh Inner Join headH on Havaleh.Id_Havaleh = Headh.Id_Havaleh
        Where Convert(Varchar(10), Tarikh_Faktor, 111) >= @Date1
        And Convert(Varchar(10), Tarikh_Faktor, 111) <= @Date2
        And Havaleh.K_Code  = (Case When @Kcode = '' then Havaleh.K_Code  Else @Kcode end)
       Group By K_Code, Kind_Flag, Sender, Reciver
      ) as T Group By K_code
     ) As T1 on T.A_Code = T1.A_Code And T.K_Code = T1.K_Code
  ------------------------------------------------------------
  END
RETURN
END
