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

namespace GZ_LTHReportForms.JiXiaoKanBan
{
    [Description("【列表插件】绩效看板汇总报表【报表】"), HotUpdate]
    public class ResultsKanbanSumReport : SysReportBaseService
    {
        /// <summary>
        /// 初始化
        /// </summary>
        public override void Initialize()
        {
            base.Initialize();
            this.ReportProperty.ReportName = new LocaleValue("绩效看板汇总", base.Context.UserLocale.LCID);
            this.ReportProperty.IsUIDesignerColumns = false;
            // 简单账表类型：普通、树形、分页
            this.ReportProperty.ReportType = ReportType.REPORTTYPE_NORMAL;
            this.IsCreateTempTableByPlugin = true;
            // 
            this.IsCreateTempTableByPlugin = true;
            //支持分组汇总
            this.ReportProperty.IsGroupSummary = true;
            // 
            this.ReportProperty.SimpleAllCols = false;
            // 
            this.ReportProperty.IsDefaultOnlyDspSumAndDetailData = true;

            // 设置精度控制
            var list = new List<DecimalControlField>
            {
                new DecimalControlField("FDECIMALS", "OrigInvoiceAmount"),
                new DecimalControlField("FDECIMALS", "ExchangeRate"),
                new DecimalControlField("FDECIMALS", "InvoiceAmountTHB"),
                new DecimalControlField("FDECIMALS", "MonthEndExRate"),
                new DecimalControlField("FDECIMALS", "RevaluationAountInTHB"),
                new DecimalControlField("FDECIMALS", "UnrealizedGainLoss"),
            };
            this.ReportProperty.DecimalControlFieldList = list;
        }

        /// <summary>
        /// 报表列表头
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public override ReportHeader GetReportHeaders(IRptParams filter)
        {
            DynamicObject customFilter = filter.FilterParameter.CustomFilter;

            base.GetReportHeaders(filter);

            ReportHeader header = new ReportHeader();


            // 下单时间
            int currentYear = DateTime.Now.Year;


            string fDate = (customFilter["FSDate"] == null) ? Convert.ToString(currentYear) : Convert.ToDateTime(
                customFilter["FSDate"]).ToString("yyyy-MM-dd");

            int year = Convert.ToInt32(fDate.Split('-')[0]);

            header.AddChild("F_SBU", new LocaleValue("SBU"), SqlStorageType.Sqlvarchar);
            header.AddChild("F_MXQY", new LocaleValue("明细区域"), SqlStorageType.Sqlvarchar);
            header.AddChild("销售员", new LocaleValue("销售员"), SqlStorageType.Sqlvarchar);
            header.AddChild("本年业绩目标_万元", new LocaleValue("" + year + "年业绩目标（万元）"), SqlStorageType.SqlDecimal);
            header.AddChild("本年派诺业绩_万元", new LocaleValue("" + year + "派诺业绩（万元）"), SqlStorageType.SqlDecimal);
            header.AddChild("本年兴诺业绩_万元", new LocaleValue("" + year + "兴诺业绩（万元）"), SqlStorageType.SqlDecimal);
            header.AddChild("本年武汉派诺_万元", new LocaleValue("" + year + "武汉派诺（万元）"), SqlStorageType.SqlDecimal);
            header.AddChild("本年碳索业绩_万元", new LocaleValue("" + year + "碳索业绩（万元）"), SqlStorageType.SqlDecimal);
            header.AddChild("本年香港派诺业绩_万元", new LocaleValue("" + year + "香港派诺业绩（万元）"), SqlStorageType.SqlDecimal);
            header.AddChild("本年华夏云联业绩_万元", new LocaleValue("" + year + "华夏云联业绩（万元）"), SqlStorageType.SqlDecimal);
            header.AddChild("往年订单变更金额_万元", new LocaleValue("往年订单变更金额（万元）"), SqlStorageType.SqlDecimal);
            header.AddChild("本年业绩合计_万元", new LocaleValue("" + year + "合计业绩额（万元）"), SqlStorageType.SqlDecimal);
            header.AddChild("达标率", new LocaleValue("达标率"), SqlStorageType.Sqlvarchar);
            header.AddChild("去年合计业绩额_万元", new LocaleValue("" + (year - 1) + "合计业绩额（万元）"), SqlStorageType.SqlDecimal);
            header.AddChild("同比增长率", new LocaleValue("同比增长率"), SqlStorageType.Sqlvarchar);
            header.AddChild("本年回款目标_万元", new LocaleValue("" + year + "回款目标（万元）"), SqlStorageType.SqlDecimal);
            header.AddChild("回款额_万元", new LocaleValue("回款额（万元）"), SqlStorageType.SqlDecimal);
            header.AddChild("回款率", new LocaleValue("回款率"), SqlStorageType.Sqlvarchar);
            header.AddChild("已发货应收款_万元", new LocaleValue("已发货应收款（万元）"), SqlStorageType.SqlDecimal);
            header.AddChild("已到期应收款_万元", new LocaleValue("已到期应收款（万元）"), SqlStorageType.SqlDecimal);

            foreach (var item in header.GetChilds())
            {
                item.Width = 160;
            }
            return header;
        }

        /// <summary>
        /// 显示报表数据
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="tableName"></param>
        public override void BuilderReportSqlAndTempTable(IRptParams filter, string tableName)
        {
            //获取过滤条件
            string Filter = GetFilterWhere(filter);

            base.BuilderReportSqlAndTempTable(filter, tableName);

            DynamicObject customFilter = filter.FilterParameter.CustomFilter;

            // 开始日期
            string fStrartDate = (customFilter["FSDate"] == null) ? "" : Convert.ToDateTime(
                customFilter["FSDate"]).ToString("yyyy-MM-dd");

            // 结束日期
            string fEndDate = (customFilter["FEDate"] == null) ? "" : Convert.ToDateTime(
                customFilter["FEDate"]).ToString("yyyy-MM-dd");

            string sql = string.Format(@"/*dialect*/
        EXEC GZ_JXKBHZB_LTH '{0}','{1}'
        SELECT 
        ROW_NUMBER() OVER (ORDER BY F_SBU DESC) AS FID,
        ROW_NUMBER() OVER (ORDER BY F_SBU DESC) AS FIDENTITYID,
        * INTO {2} FROM JXKBHZB {3}
", fStrartDate, fEndDate, tableName, Filter);
            DBUtils.Execute(this.Context, sql);
        }

        //报表过滤条件-多选销售员
        private string GetFilterWhere(IRptParams filter)
        {
            DynamicObject customFilter = filter.FilterParameter.CustomFilter;
            StringBuilder strwhere = new StringBuilder(); //创建字符串构建器;
            strwhere.AppendLine("WHERE 1=1");
            var xsy = customFilter["F_Salesperson"] as DynamicObjectCollection;
            if (xsy.Count > 0)
            {
                List<string> xsyList = new List<string>();
                //循环获取物料信息
                foreach (DynamicObject dobj in xsy)
                {
                    DynamicObject dynamic = dobj["F_Salesperson"] as DynamicObject;
                    xsyList.Add(dynamic["Name"].ToString());
                }
                strwhere.AppendLine(string.Format(@"AND 销售员 IN ({0})", string.Join(",", xsyList.Select(x => $"'{x}'"))));
            }
            return strwhere.ToString();
        }

        //设置报表合计列
        public override List<SummaryField> GetSummaryColumnInfo(IRptParams filter)
        {
            var result = base.GetSummaryColumnInfo(filter);
            result.Add(new SummaryField("本年业绩目标_万元", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("本年派诺业绩_万元", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("本年兴诺业绩_万元", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("本年武汉派诺_万元", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("本年碳索业绩_万元", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("本年香港派诺业绩_万元", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("本年华夏云联业绩_万元", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("往年订单变更金额_万元", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("本年业绩合计_万元", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("去年合计业绩额_万元", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("回款额_万元", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("已发货应收款_万元", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("已到期应收款_万元", BOSEnums.Enu_SummaryType.SUM));
            return result;
        }

    }
}
