using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Contracts.Report;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Report;
using Kingdee.BOS.Core.SqlBuilder;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;

namespace GZ_LTHReportForms.YingShouBaoBiao
{
    [Description("应收情况概况表按(SBU)区分"), HotUpdate]
    public class YingShouSBU : SysReportBaseService
    {
        public override void Initialize()
        {
            base.Initialize();
            //设置报表类型为普通类型
            this.ReportProperty.ReportType = ReportType.REPORTTYPE_NORMAL;
            //设置是否通过插件创建临时表
            this.IsCreateTempTableByPlugin = true;
            //设置是否分组汇总
            this.ReportProperty.IsGroupSummary = true;

        }
        //获取过滤条件信息(构造单据信息)
        public override ReportTitles GetReportTitles(IRptParams filter)
        {
            //创建标题对象
            ReportTitles reportTitles = new ReportTitles();
            //获取自定义过滤条件
            DynamicObject customFilter = filter.FilterParameter.CustomFilter;
            if (customFilter != null)
            {
                //获取组织名称
                string multiOrgnNameValues = this.GetMultiOrgnNameValues(customFilter["F_YKQC_OrgId_uky"] as DynamicObject);
                //添加标题
                reportTitles.AddTitle("F_YKQC_OrgId_re5", multiOrgnNameValues);
            }
            //返回标题
            return reportTitles;
        }
        //获取组织名称
        private string GetMultiOrgnNameValues(DynamicObject orgIdStrings)
        {
            //获取组织名称
            List<string> list = new List<string>();
            //初始化结果字符串
            string result = string.Empty;
            //如果组织ID字符串不为空
            if (orgIdStrings != null)
            {
                //获取查询服务
                IQueryService service = Kingdee.BOS.Contracts.ServiceFactory.GetService<IQueryService>(base.Context);
                //创建查询参数
                QueryBuilderParemeter para = new QueryBuilderParemeter
                {
                    FormId = "ORG_Organizations",
                    //查询组织名称
                    SelectItems = SelectorItemInfo.CreateItems("FNAME"),
                    //过滤条件，根据组织ID和区域ID
                    FilterClauseWihtKey = string.Format("FORGID IN ({0}) AND FLOCALEID = {1}", orgIdStrings["Id"].Long2Int(), base.Context.UserLocale.LCID)
                };
                //获取动态对象集合
                DynamicObjectCollection dynamicObjects = service.GetDynamicObjectCollection(base.Context, para, null);
                //遍历获取到的动态对象
                foreach (DynamicObject current in dynamicObjects)
                {
                    //将组织名称添加到列表
                    list.Add(current["FNAME"].ToString());
                }
                //如果列表不为空
                if (list.Count > 0)
                {
                    result = string.Join(",", list.ToArray());
                }
            }
            //返回组织名称字符串
            return result;
        }

        //设置单据列
        public override ReportHeader GetReportHeaders(IRptParams filter)
        {
            //创建表头对象
            ReportHeader header = new ReportHeader();
            header.AddChild("SBU", new LocaleValue("SBU", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("年底到期应收款额", new LocaleValue("期初到期应收额", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("年底到期应收款专责小组", new LocaleValue("其中:期初应收款专责小组", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("到期应收款额", new LocaleValue("本月到期应收额", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("应收款专责小组", new LocaleValue("其中:本月应收款专责小组", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("占比", new LocaleValue("占比", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("变化", new LocaleValue("变化", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            foreach(var item in header.GetChilds())
            {
                item.Width = 200;
            }
            return header;
        }

        //创建临时表
        public override void BuilderReportSqlAndTempTable(IRptParams filter, string tableName)
        {
            //获取过滤条件
            string Filter = GetFilterWhere(filter);
            /*
                取数SQL
                SQL查询字符串，提取所需数据并将结果存入临时表
             */
            string sql = String.Format(@"/*dialect*/
DECLARE @ResultDate VARCHAR(1000);
DECLARE @ThisDate VARCHAR(1000);
DECLARE @SUMDQ DECIMAL(10, 2);


-- 取上一年的年底日期
SET @ResultDate = FORMAT(DATEADD(DAY, -1, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0)),'yyyy-MM-dd');
--取当天日期
SET @ThisDate = FORMAT(GETDATE(),'yyyy-MM-dd')

SELECT W.*,x.FNAME into #RecCond FROM  T_SAL_ORDERPLAN W       
INNER JOIN T_BD_RecCondition_L X on X.FID = W.F_RecConditionId       
      
SELECT  D.FID,sum(b.fqty) AS 'FQTY',sum(E.fallamount) AS 'FAMOUNT'       
  INTO #SAL      
  FROM T_SAL_DELIVERYNOTICE A       
  INNER JOIN T_SAL_DELIVERYNOTICEENTRY B ON A.FID = B.FID       
  INNER JOIN T_SAL_DELIVERYNOTICEENTRY_F E ON E.FENTRYID = B.FENTRYID      
  INNER JOIN T_SAL_DELIVERYNOTICEENTRY_LK  C ON C.FENTRYID = B.FENTRYID       
  INNER JOIN T_SAL_ORDERENTRY D ON D.FID = C.FSBILLID  AND D.FENTRYID = C.FSID      
  WHERE A.FDOCUMENTSTATUS= 'C'      
  GROUP BY D.FID      
      
      
  SELECT  D.FID,sum(b.fqty) AS 'FQTY',sum(E.fallamount) AS 'FAMOUNT'       
  INTO #RETURN      
  FROM T_SAL_RETURNNOTICE  A       
  INNER JOIN T_SAL_RETURNNOTICEENTRY  B ON A.FID = B.FID       
  INNER JOIN T_SAL_RETURNNOTICEENTRY_F E ON E.FENTRYID = B.FENTRYID      
  INNER JOIN T_SAL_RETURNNOTICEENTRY_LK  C ON C.FENTRYID = B.FENTRYID       
  INNER JOIN T_SAL_ORDERENTRY D ON D.FID = C.FSBILLID  AND D.FENTRYID = C.FSID       
  WHERE A.FDOCUMENTSTATUS= 'C'      
  GROUP BY D.FID      
      
      
  SELECT  F.FID,sum(b.FREALQTY) AS 'FQTY',sum(G.FALLAMOUNT_LC) AS 'FAMOUNT'      
  INTO #OUTSTOCK      
  FROM  T_SAL_OUTSTOCK A       
  INNER JOIN T_SAL_OUTSTOCKENTRY B ON A.FID = B.FID       
  INNER JOIN T_SAL_OUTSTOCKENTRY_F G ON G.FENTRYID = B.FENTRYID      
  INNER JOIN T_SAL_OUTSTOCKENTRY_LK C ON C.FENTRYID = B.FENTRYID      
  INNER JOIN T_SAL_DELIVERYNOTICEENTRY  D ON D.FID = C.FSBILLID AND D.FENTRYID = C.FSID      
  INNER JOIN T_SAL_DELIVERYNOTICEENTRY_LK E ON E.FENTRYID = D.FENTRYID        
  INNER JOIN T_SAL_ORDERENTRY F ON F.FID = E.FSBILLID  AND F.FENTRYID = E.FSID      
  WHERE A.FDOCUMENTSTATUS= 'C'      
  GROUP BY F.FID      
      
  SELECT  F.FID,sum(b.FREALQTY) AS 'FQTY',sum(G.FALLAMOUNT_LC) AS 'FAMOUNT'       
  INTO #RETURNSTOCK      
  FROM T_SAL_RETURNSTOCK A       
  INNER JOIN T_SAL_RETURNSTOCKENTRY B ON A.FID = B.FID       
  INNER JOIN T_SAL_RETURNSTOCKENTRY_F G ON G.FENTRYID = B.FENTRYID      
  INNER JOIN T_SAL_RETURNSTOCKENTRY_LK C ON C.FENTRYID = B.FENTRYID      
  INNER JOIN T_SAL_RETURNNOTICEENTRY  D ON D.FID = C.FSBILLID AND D.FENTRYID = C.FSID      
  INNER JOIN T_SAL_RETURNNOTICEENTRY_LK E ON E.FENTRYID = D.FENTRYID        
  INNER JOIN T_SAL_ORDERENTRY F ON F.FID = E.FSBILLID  AND F.FENTRYID = E.FSID      
  WHERE A.FDOCUMENTSTATUS= 'C'      
  GROUP BY F.FID      
      
  SELECT  b.FORDERENTRYID as 'FENTRYID',sum(b.FPriceQty) AS 'FQTY',sum(b.FALLAMOUNT) AS 'FAMOUNT'      
  INTO #RECE      
  FROM t_AR_receivable A       
  INNER JOIN t_AR_receivableENTRY B ON A.FID = B.FID         
  WHERE A.FDOCUMENTSTATUS= 'C'      
  GROUP BY b.FORDERENTRYID 

SELECT 
CASE WHEN ISNULL(O.FNAME,'') = '' THEN AC.区域   
ELSE ACC.区域 END  AS 'SBU',
CASE WHEN ROW_NUMBER() OVER (PARTITION BY A.Fid,n.FSaleId,X.FNAME ORDER BY n.FSaleId,X.FNAME) != 1 THEN null   
 WHEN X.FNAME in ('预付款(仪表)','预付款(系统)') THEN null    
 WHEN X.FNAME in ('货到收款(仪表)','货到收款(系统)') AND DATEADD(day, W.F_DAY, CK.F_SFSIGNATURETIME) < @ResultDate AND W.FRECADVANCERATE = 100 THEN ISNULL(Q.累计发货金额,0)-ISNULL(v.累计退货金额,0)    
 WHEN X.FNAME in ('货到收款(仪表)','货到收款(系统)') AND DATEADD(day, W.F_DAY, CK.F_SFSIGNATURETIME) < @ResultDate THEN ISNULL(W.F_MBBA_Decimal_uky,0)     
 WHEN X.FNAME in ('货到票到收款(系统)','货到票到收款(仪表)') AND DATEADD(day, W.F_DAY,FP.F_DATE) < @ResultDate AND W.FRECADVANCERATE = 100 THEN ISNULL(Q.累计发货金额,0)-ISNULL(v.累计退货金额,0)    
 WHEN X.FNAME in ('货到票到收款(系统)','货到票到收款(仪表)') AND DATEADD(day, W.F_DAY,FP.F_DATE) < @ResultDate THEN ISNULL(W.F_MBBA_Decimal_uky,0)     
 WHEN X.FNAME in ('款到发货(仪表)','款到发货(系统)') AND DATEADD(day, W.F_DAY,Q.发货日期) < @ResultDate AND W.FRECADVANCERATE = 100 THEN ISNULL(Q.累计发货金额,0)-ISNULL(v.累计退货金额,0)    
 WHEN X.FNAME in ('款到发货(仪表)','款到发货(系统)') AND DATEADD(day, W.F_DAY,Q.发货日期) < @ResultDate THEN ISNULL(W.F_MBBA_Decimal_uky,0)     
 ELSE null--款到发货(仪表)    
 END AS '年底到期应收款额',
CASE WHEN ROW_NUMBER() OVER (PARTITION BY A.Fid,n.FSaleId,X.FNAME ORDER BY n.FSaleId,X.FNAME) != 1 THEN null   
 WHEN X.FNAME in ('预付款(仪表)','预付款(系统)') THEN null    
 WHEN X.FNAME in ('货到收款(仪表)','货到收款(系统)') AND isnull(ROUND( DATEDIFF(DAY,convert(nvarchar(10),dateadd(day,isnull(w.f_day,0) ,W.F_PMSDate),23),@ResultDate) / 30,0) ,0)>=6 AND W.FRECADVANCERATE = 100 THEN ISNULL(Q.累计发货金额,0)-ISNULL(v.累计退货金额,0)    
 WHEN X.FNAME in ('货到收款(仪表)','货到收款(系统)') AND isnull(ROUND( DATEDIFF(DAY,convert(nvarchar(10),dateadd(day,isnull(w.f_day,0) ,W.F_PMSDate),23),@ResultDate) / 30,0) ,0)>=6 THEN ISNULL(W.F_MBBA_Decimal_uky,0)     
 WHEN X.FNAME in ('货到票到收款(系统)','货到票到收款(仪表)') AND isnull(ROUND( DATEDIFF(DAY,convert(nvarchar(10),dateadd(day,isnull(w.f_day,0) ,W.F_PMSDate),23),@ResultDate) / 30,0) ,0)>=6 AND W.FRECADVANCERATE = 100 THEN ISNULL(Q.累计发货金额,0)-ISNULL(v.累计退货金额,0)    
 WHEN X.FNAME in ('货到票到收款(系统)','货到票到收款(仪表)') AND isnull(ROUND( DATEDIFF(DAY,convert(nvarchar(10),dateadd(day,isnull(w.f_day,0) ,W.F_PMSDate),23),@ResultDate) / 30,0) ,0)>=6 THEN ISNULL(W.F_MBBA_Decimal_uky,0)     
 WHEN X.FNAME in ('款到发货(仪表)','款到发货(系统)') AND isnull(ROUND( DATEDIFF(DAY,convert(nvarchar(10),dateadd(day,isnull(w.f_day,0) ,W.F_PMSDate),23),@ResultDate) / 30,0) ,0)>=6 AND W.FRECADVANCERATE = 100 THEN ISNULL(Q.累计发货金额,0)-ISNULL(v.累计退货金额,0)    
 WHEN X.FNAME in ('款到发货(仪表)','款到发货(系统)') AND isnull(ROUND( DATEDIFF(DAY,convert(nvarchar(10),dateadd(day,isnull(w.f_day,0) ,W.F_PMSDate),23),@ResultDate) / 30,0) ,0)>=6 THEN ISNULL(W.F_MBBA_Decimal_uky,0)     
 ELSE null--款到发货(仪表)    
 END AS '年底到期应收款专责小组',
CASE WHEN ROW_NUMBER() OVER (PARTITION BY A.Fid,n.FSaleId,X.FNAME ORDER BY n.FSaleId,X.FNAME) != 1 THEN null   
 WHEN X.FNAME in ('预付款(仪表)','预付款(系统)') THEN null    
 WHEN X.FNAME in ('货到收款(仪表)','货到收款(系统)') AND DATEADD(day, W.F_DAY, CK.F_SFSIGNATURETIME) < @ThisDate AND W.FRECADVANCERATE = 100 THEN ISNULL(Q.累计发货金额,0)-ISNULL(v.累计退货金额,0)    
 WHEN X.FNAME in ('货到收款(仪表)','货到收款(系统)') AND DATEADD(day, W.F_DAY, CK.F_SFSIGNATURETIME) < @ThisDate THEN ISNULL(W.F_MBBA_Decimal_uky,0)     
 WHEN X.FNAME in ('货到票到收款(系统)','货到票到收款(仪表)') AND DATEADD(day, W.F_DAY,FP.F_DATE) < @ThisDate AND W.FRECADVANCERATE = 100 THEN ISNULL(Q.累计发货金额,0)-ISNULL(v.累计退货金额,0)    
 WHEN X.FNAME in ('货到票到收款(系统)','货到票到收款(仪表)') AND DATEADD(day, W.F_DAY,FP.F_DATE) < @ThisDate THEN ISNULL(W.F_MBBA_Decimal_uky,0)     
 WHEN X.FNAME in ('款到发货(仪表)','款到发货(系统)') AND DATEADD(day, W.F_DAY,Q.发货日期) < @ThisDate AND W.FRECADVANCERATE = 100 THEN ISNULL(Q.累计发货金额,0)-ISNULL(v.累计退货金额,0)    
 WHEN X.FNAME in ('款到发货(仪表)','款到发货(系统)') AND DATEADD(day, W.F_DAY,Q.发货日期) < @ThisDate THEN ISNULL(W.F_MBBA_Decimal_uky,0)     
 ELSE null--款到发货(仪表)    
 END AS '到期应收款额',
CASE WHEN ROW_NUMBER() OVER (PARTITION BY A.Fid,n.FSaleId,X.FNAME ORDER BY n.FSaleId,X.FNAME) != 1 THEN null   
 WHEN X.FNAME in ('预付款(仪表)','预付款(系统)') THEN null    
 WHEN X.FNAME in ('货到收款(仪表)','货到收款(系统)') AND isnull(ROUND( DATEDIFF(DAY,convert(nvarchar(10),dateadd(day,isnull(w.f_day,0) ,W.F_PMSDate),23),@ThisDate) / 30,0) ,0)>=6 AND W.FRECADVANCERATE = 100 THEN ISNULL(Q.累计发货金额,0)-ISNULL(v.累计退货金额,0)    
 WHEN X.FNAME in ('货到收款(仪表)','货到收款(系统)') AND isnull(ROUND( DATEDIFF(DAY,convert(nvarchar(10),dateadd(day,isnull(w.f_day,0) ,W.F_PMSDate),23),@ThisDate) / 30,0) ,0)>=6 THEN ISNULL(W.F_MBBA_Decimal_uky,0)     
 WHEN X.FNAME in ('货到票到收款(系统)','货到票到收款(仪表)') AND isnull(ROUND( DATEDIFF(DAY,convert(nvarchar(10),dateadd(day,isnull(w.f_day,0) ,W.F_PMSDate),23),@ThisDate) / 30,0) ,0)>=6 AND W.FRECADVANCERATE = 100 THEN ISNULL(Q.累计发货金额,0)-ISNULL(v.累计退货金额,0)    
 WHEN X.FNAME in ('货到票到收款(系统)','货到票到收款(仪表)') AND isnull(ROUND( DATEDIFF(DAY,convert(nvarchar(10),dateadd(day,isnull(w.f_day,0) ,W.F_PMSDate),23),@ThisDate) / 30,0) ,0)>=6 THEN ISNULL(W.F_MBBA_Decimal_uky,0)     
 WHEN X.FNAME in ('款到发货(仪表)','款到发货(系统)') AND isnull(ROUND( DATEDIFF(DAY,convert(nvarchar(10),dateadd(day,isnull(w.f_day,0) ,W.F_PMSDate),23),@ThisDate) / 30,0) ,0)>=6 AND W.FRECADVANCERATE = 100 THEN ISNULL(Q.累计发货金额,0)-ISNULL(v.累计退货金额,0)    
 WHEN X.FNAME in ('款到发货(仪表)','款到发货(系统)') AND isnull(ROUND( DATEDIFF(DAY,convert(nvarchar(10),dateadd(day,isnull(w.f_day,0) ,W.F_PMSDate),23),@ThisDate) / 30,0) ,0)>=6 THEN ISNULL(W.F_MBBA_Decimal_uky,0)     
 ELSE null--款到发货(仪表)    
 END AS '应收款专责小组'
INTO #TEMP1
FROM T_SAL_ORDER A --销售订单表头      
 LEFT JOIN      
 (Select a2.FENTRYID,a2.FDATAVALUE From T_BAS_ASSISTANTDATAENTRY a1 JOIN T_BAS_ASSISTANTDATAENTRY_L a2 on a1.FENTRYID = a2.FENTRYID      
 Where a1.FID = '670cc977263353') B on A.F_ORDERCATEGORY = B.FENTRYID      
 --INNER JOIN T_SAL_orderentry b on a.FID = B.FID --销售订单表体      
 INNER JOIN T_BD_CUSTOMER_L C ON C.FCUSTID= A.FCUSTID AND C.FLOCALEID= 2052 --客户附属表       
 INNER JOIN T_SAL_ORDERFIN  F ON F.FID  = A.FID       
 INNER JOIN T_BD_CUSTOMER I ON I .FCUSTID = A.FCUSTID      
 INNER JOIN T_SAL_ORDERFIN J ON J.FID= A.FID       
 LEFT JOIN  T_BAS_PREBDONE_L G ON G.FID = A.F_projectname AND G.FLocaleID =2052      
 LEFT JOIN  T_BAS_PREBDTHREE H ON H.FID = A.F_BON      
 lEFT JOIN V_ASSISTANTDATA K ON K.FENTRYID = I.FCompanyNature       
 lEFT JOIN V_BD_SALESMAN_L L ON L.fid = A.FSALERID        
 left JOIN T_PerformanceSharing M ON M.FSOURCEBILLNO = A.FBILLNO      
 left JOIN T_PerformanceSharingEntry N ON N.FID=M.FID      
 LEFT JOIN V_BD_SALESMAN_L O ON O.fid= N.FSALEID       
 LEFT JOIN V_ASSISTANTDATA P ON P.FENTRYID = I.F_CREDITCLASSIFICATION      
 LEFT JOIN T_SAL_OUTSTOCK CK on CK.F_CONTRACTNUMBER = A.F_CONTRACTNUMBER --销售出库单      
 LEFT JOIN T_IV_SALESIC FP on FP.F_PAPERNUMBER = A.F_CONTRACTNUMBER --销售增值税专用发票      
 LEFT JOIN       
 (      
  SELECT F_Papercontract,MAX(CONVERT(NVARCHAR(10), A.FDATE,23)) AS '发货日期',SUM(B.FBILLALLAMOUNT_LC) AS '累计发货金额'  FROM T_SAL_DELIVERYNOTICE A         
  INNER JOIN T_SAL_DELIVERYNOTICEFIN B ON A.FID =B.FID       
  WHERE A.FDOCUMENTSTATUS= 'C'      
  GROUP BY A.F_Papercontract      
 ) Q ON Q.F_PAPERCONTRACT = A.F_contractnumber --获取发货通知单最大的发货日期      
 LEFT JOIN T_META_FORMENUMITEM R ON r.FVALUE  = A.F_OrderType AND R.FID =  'bc2c1d77-0f4b-41d2-b61b-e29554c570d4'      
 LEFT JOIN T_META_FORMENUMITEM_L S ON S.FENUMID = R.FENUMID AND S.FLOCALEID = 2052        
 LEFT JOIN       
 (      
  SELECT F_Paper ,CONVERT(NVARCHAR(10), MAX(FDATE),23) AS '开票日期',CONVERT(NVARCHAR(10),      
  MAX(FDATE),23) AS '没有红色的开票日期'       
  FROM t_AR_receivable A        
  INNER JOIN T_AR_RECEIVABLEENTRY B ON A.FID = B.FID       
  WHERE A.FDOCUMENTSTATUS = 'C' AND A.FCancelStatus = 'A'      
  GROUP BY F_Paper      
 ) T ON T.F_PAPER = A.F_contractnumber      
 LEFT JOIN V_ASSISTANTDATA U ON U.FENTRYID = A.F_Ordercategory      
 LEFT JOIN       
 (      
  SELECT F_contractnumber,MAX(CONVERT(NVARCHAR(10), A.FDATE,23)) AS '退货日期',SUM(B.FBILLALLAMOUNT_LC) AS '累计退货金额'  FROM T_SAL_RETURNSTOCK A         
  INNER JOIN T_SAL_RETURNSTOCKFIN B ON A.FID =B.FID       
  WHERE A.FDOCUMENTSTATUS= 'C'      
  GROUP BY A.F_contractnumber      
 ) V ON V.F_contractnumber = A.F_contractnumber --获取销售退货单       
 LEFT JOIN  ERPTOHR.HYHRV3.dbo.v_erp_empinfo AC ON AC.名称=L.FNAME        
 LEFT JOIN  ERPTOHR.HYHRV3.dbo.v_erp_empinfo ACC ON ACC.名称=O.FNAME        
 --LEFT JOIN  temp20241206 AC ON AC.名称=L.FNAME        
 --LEFT JOIN  temp20241206 ACC ON ACC.名称=O.FNAME        
 LEFT JOIN T_SAL_ORDERPLAN W ON W.FID= A.FID       
 LEFT JOIN T_BD_RecCondition_L X on X.FID = W.F_RecConditionId       
 LEFT JOIN  #RecCond Y ON Y.FID =A.FID  AND Y.FNAME LIKE '%质保金%'        
 LEFT JOIN  (select distinct fid from #RecCond Z where Z.FNAME LIKE '%款到%') z on z.fid =a.fid       
 LEFT JOIN  (select distinct fid from #RecCond AA where AA.FNAME LIKE '%协议%') AA on AA.fid =a.fid        
 LEFT JOIN (SELECT distinct F_Papercontract FROM T_SAL_DELIVERYNOTICE WHERE F_SFYFH ='是') AB ON AB.F_PAPERCONTRACT = A.F_contractnumber      
 LEFT JOIN       
 (      
  SELECT       
  F_Papercontract,CAST( sum(b.FALLAMOUNT) AS REAL) AS '发票总金额',      
  CAST (sum(CASE WHEN F_Papercontract  = 'Y' THEN b.FALLAMOUNT ELSE 0 END  ) AS REAL) AS '发票总金额(普票存财务)'      
  FROM t_AR_receivable A      
  INNER JOIN T_AR_RECEIVABLEFIN B ON A.FID = B.FID       
  GROUP BY F_Papercontract      
 ) AD ON AD.F_PAPERCONTRACT = A.F_contractnumber      
 LEFT JOIN      
 (      
  SELECT a.F_Papercontract,      
  avg(d.FCURWRITTENOFFAMOUNT) as '累计收款'       
        
  FROM t_AR_receivable A        
  INNER JOIN T_AR_RECEIVABLEENTRY E ON E.FID =A.FID       
  INNER JOIN T_AR_RECMacthLogENTRY B ON A.FBILLNO = B.FSRCBILLNO      
  INNER JOIN T_AR_RECMacthLog C ON C.FID = B.FID       
  INNER JOIN T_AR_RECMacthLogENTRY D ON D.FID = B.FID      
  AND D.FSOURCETYPE = '36cf265bd8c3452194ed9c83ec5e73d2'       
  WHERE       
  1=1         
  group by a.F_Papercontract      
 ) AE ON AE.F_Papercontract = A.F_contractnumber      
 WHERE 1=1 AND A.FDOCUMENTSTATUS = 'C'  AND B.FDATAVALUE != 'Z'               
 AND ((F.FBILLALLAMOUNT_LC * isnull(n.FSHARERATE,100) /100)!=0)     
{1}
ORDER BY A.F_contractnumber 

SELECT @SUMDQ = SUM(到期应收款额) FROM #TEMP1

SELECT 
    SBU AS SBU1,
    CONVERT(DECIMAL(10, 2),SUM(ISNULL(年底到期应收款额, 0)),2) AS '总年底到期应收款额',
    CONVERT(DECIMAL(10, 2),SUM(ISNULL(到期应收款额, 0)),2) AS '总到期应收款额',
    CONVERT(DECIMAL(10, 2),SUM(ISNULL(年底到期应收款专责小组, 0)),2) AS '年底到期应收款专责小组',
    CONVERT(DECIMAL(10, 2),SUM(ISNULL(应收款专责小组, 0)),2) AS '应收款专责小组',
    '' AS '占比',
    0 AS '变化'
    INTO #TEMP2
FROM 
    #TEMP1
GROUP BY 
    SBU
ORDER BY 
    SBU DESC;

ALTER TABLE #TEMP2
ALTER COLUMN 占比 NVARCHAR(100);

UPDATE #TEMP2
SET 占比 = CASE 
    WHEN 总到期应收款额 = 0 THEN '' -- 防止除以0
    ELSE CONVERT(nvarchar(10), CONVERT(DECIMAL(10, 2), (总到期应收款额 / @SUMDQ) * 100),2) + '%'
END;

UPDATE #TEMP2
SET 变化 = CONVERT(DECIMAL(10, 2),(总到期应收款额 - 总年底到期应收款额),2)

SELECT
ROW_NUMBER() OVER (ORDER BY B.SBU1 DESC) AS FID,
ROW_NUMBER() OVER (ORDER BY B.SBU1 DESC) AS FIDENTITYID,
B.SBU1 AS 'SBU',
CASE 
WHEN B.总年底到期应收款额 = 0 THEN null
ELSE B.总年底到期应收款额 END AS '年底到期应收款额',
CASE 
WHEN B.年底到期应收款专责小组 = 0 THEN null
ELSE B.年底到期应收款专责小组 END AS '年底到期应收款专责小组',
CASE 
WHEN B.总到期应收款额  = 0 THEN null
ELSE B.总到期应收款额  END AS '到期应收款额',
CASE 
WHEN B.应收款专责小组 = 0 THEN null
ELSE B.应收款专责小组 END AS '应收款专责小组',
B.占比 AS '占比',
B.变化 AS '变化' 
INTO {0} FROM #TEMP2 B
GROUP BY B.年底到期应收款专责小组,B.应收款专责小组,B.SBU1,B.总年底到期应收款额,B.总到期应收款额,B.占比,B.变化
", tableName,Filter);
            //执行SQL并动态创建报表
            DBUtils.ExecuteDynamicObject(this.Context, sql);
        }

        //获取过滤条件
        private string GetFilterWhere(IRptParams fileter)
        {
            //获取自定义过滤条件
            DynamicObject customFilter = fileter.FilterParameter.CustomFilter;
            //创建字符串构建器
            StringBuilder strwhere = new StringBuilder();
            var orgFid = customFilter["F_YKQC_OrgId_uky"] as DynamicObject;
            if (orgFid != null)
            {
                string org = string.IsNullOrWhiteSpace(customFilter["F_YKQC_OrgId_uky"].ToString()) ? "" :
                    string.Format("AND A.FSaleOrgId IN ({0})", orgFid["Id"].Long2Int());
                //添加组织过滤条件
                strwhere.AppendLine(org);
            }
            return strwhere.ToString();
        }
        //添加合计列
        public override List<SummaryField> GetSummaryColumnInfo(IRptParams filter)
        {
            var result = base.GetSummaryColumnInfo(filter);
            result.Add(new SummaryField("年底到期应收款额", Kingdee.BOS.Core.Enums.BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("到期应收款额",Kingdee.BOS.Core.Enums.BOSEnums.Enu_SummaryType.SUM));
            return result;
        }

    }
}
