using BPA.MES.Base.Application.Services.ReportService.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BPA.MES.Base.Application.Services.ReportService
{

    [ApiDescriptionSettings("统计报表管理", Order = 2, Name = "Report", Tag = "报表信息", KeepName = true, SplitCamelCase = true, KeepVerb = true)]
    public class ReportService : IReportService, ITransient, IDynamicApiController
    {
        private readonly ISqlSugarClient _dbContext;
        public ReportService(ISqlSugarClient db)
        {
            _dbContext = db;
        }

        /// <summary>
        /// 获取成品生产统计
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<SqlSugarPagedList<ProductOutDto>> GetProductReport(ProductInputDto input)
        {
            var res = await _dbContext.Queryable<Pztj_WorkInfoEntity>().LeftJoin<Pztj_FinalsInfoEntity>((a, b) => a.FinalId == b.Id)
                .WhereIF(!string.IsNullOrEmpty(input.ProductName), (a, b) => b.Name.Contains(input.ProductName))
                .WhereIF(input.StartTime.HasVal(), (a, b) => a.CreateTime >= input.StartTime.Value)
                .WhereIF(input.EndTime.HasVal(), (a, b) => a.CreateTime <= input.EndTime.Value)
                .Where((a, b) => a.Status == WorkOrderStatusEnum.Completed)
                .GroupBy((a, b) => b.Name)
                .Select((a, b) => new ProductOutDto
                {
                    ProductName = b.Name,
                    Count = SqlFunc.AggregateSum(Convert.ToDecimal(a.Number)),

                }).ToPagedListAsync(input.PageIndex, input.PageSize);

            return res;
        }


        /// <summary>
        /// 获取物料统计
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<SqlSugarPagedList<MaterialsOutDto>> GetMaterialsReport(MaterialsInputDto input)
        {
            var result = await _dbContext.Queryable<WorkInfoMaterialsRecordEntity>()
                .LeftJoin<Pztj_WorkInfoEntity>((a, b) => a.WorkId == b.Id)
                .Where((a, b) => b.Status == WorkOrderStatusEnum.Completed)
              .WhereIF(!string.IsNullOrEmpty(input.MaterialName), (a, b) => a.MaterialName.Contains(input.MaterialName))
               .WhereIF(input.StartTime.HasVal(), (a, b) => b.CreateTime >= input.StartTime.Value)
                .WhereIF(input.EndTime.HasVal(), (a, b) => b.CreateTime <= input.EndTime.Value)
            .GroupBy((a, b) => a.MaterialName)
                .Select((a, b) => new MaterialsOutDto
                {
                    Count = SqlFunc.AggregateSumNoNull(Convert.ToDecimal(a.Weight)),
                    MaterialName = a.MaterialName,
                }).ToPagedListAsync(input.PageIndex, input.PageSize);

            return result;
        }
    }
}
