using Furion.DependencyInjection;
using Mapster;
using Nirvana.Common;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YBDevice.Entity;

namespace YBDevice.Application.ReportInfo
{
    /// <summary>
    /// 统计管理
    /// </summary>
    public class ReportService :IReportService, ITransient
    {
        private readonly ISqlSugarRepository<YB_Combined> repository;
        private readonly SqlSugarClient dbClient;
        private readonly OperatorModel currentUser;
        public ReportService(ISqlSugarRepository<YB_Combined> sqlSugarRepository)
        {
            repository = sqlSugarRepository;
            dbClient = repository.Context;
            currentUser = BaseInfoService.GetUserInfo();
        }
        /// <summary>
        /// 获取合计信息
        /// </summary>
        /// <returns></returns>
        public async Task<YB_Combined> GetCombinedInfoAsync()
        {
            var data = new YB_Combined
            {
                TodayRegCnt = 0,
                TodayDevCnt = 0,
                TotalDevCnt = 0,
                TodayIncome = 0,
                TodayResultCnt = 0,
                TotalIncome = 0,
                TotalRegCnt = 0,
                TotalResultCnt = 0
            };
            if (currentUser.AccountType != AccountType.platform)
            {
                var businessdata = await dbClient.Queryable<YB_BusinessRealData>().FirstAsync(x => x.BusinessId == currentUser.BusinessId);
                if(businessdata != null)
                {
                    data.TodayDevCnt = businessdata.TodayDevCount;
                    data.TotalDevCnt = businessdata.DevCount;
                    data.TodayResultCnt = businessdata.TodayResultCnt;
                    data.TotalResultCnt = businessdata.TotalResultCnt;
                }
            }
            else
            {
                var totaldata = await dbClient.Queryable<YB_Combined>().FirstAsync(x => x.Id == 1);
                if (totaldata != null)
                {
                    data = totaldata;
                }
            }
            return data;
        }
        /// <summary>
        /// 获取指定设备统计数据
        /// </summary>
        /// <param name="id"></param>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <returns></returns>
        public async Task<List<ReportChartDto>> GetDevListAsync(int id, DateTime? starttime, DateTime? endtime)
        {
            if (!starttime.HasValue)
            {
                starttime = DateTime.Now.AddDays(-7).Date;
            }
            if (!endtime.HasValue)
            {
                endtime = DateTime.Now.AddDays(-1).Date;
            }
            var tempquery = dbClient.Queryable<YB_DeviceDayReportData>()
                .Where(x => x.DevId == id && x.RecordTime >= starttime && x.RecordTime <= endtime);
            if(currentUser.AccountType != AccountType.platform)
            {
                if(currentUser.Type == 2)
                {
                    tempquery = tempquery.Where(x => x.BusinessId == currentUser.BusinessId);
                }
                else
                {
                    tempquery = tempquery.Where(x => SqlFunc.Subqueryable<YB_Business>().Where(e =>SqlFunc.StartsWith(e.Code,currentUser.BusinessCode)&&e.Id == x.BusinessId).Any());
                }
            }
            var query = await tempquery.OrderBy(x => x.RecordTime, OrderByType.Asc)
                .GroupBy(x=>new { 
                    x.DevId,
                    x.RecordTime
                })
                .Select(x => new YB_DayReport
            {
                DayDevCnt = 0,
                DayInCome = SqlFunc.AggregateSum(x.DayInCome),
                DayRegCnt = 0,
                DayResultCnt = SqlFunc.AggregateSum(x.DayResultCnt),
                RecordTime = x.RecordTime
            })
                .ToListAsync();
            var list = query.Adapt<List<ReportChartDto>>();
            return list;
        }

        /// <summary>
        /// 获取日统计数据
        /// </summary>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <returns></returns>
        public async Task<List<ReportChartDto>> GetListAsync(DateTime? starttime, DateTime? endtime)
        {
            if (!starttime.HasValue)
            {
                starttime = DateTime.Now.AddDays(-7).Date;
            }
            if (!endtime.HasValue)
            {
                endtime = DateTime.Now.AddDays(-1).Date;
            }
            if (currentUser.AccountType != AccountType.platform)
            {
                var tempquery = dbClient.Queryable<YB_BusinessReportData>().Where(x => x.RecordTime >= starttime && x.RecordTime <= endtime);
                if (currentUser.Type == 2)
                {
                    tempquery = tempquery.Where(x => x.BusinessId == currentUser.BusinessId);
                }
                else
                {
                    tempquery = tempquery.Where(x => SqlFunc.Subqueryable<YB_Business>().Where(e => SqlFunc.StartsWith(e.Code, currentUser.BusinessCode) && e.Id == x.BusinessId).Any());
                }
                var query = await tempquery.OrderBy(x => x.RecordTime, OrderByType.Asc)
                    .GroupBy(x=>new
                    {
                        x.BusinessId,
                        x.RecordTime
                    })
                    .Select(x => new YB_DayReport
                {
                    DayDevCnt = SqlFunc.AggregateSum(x.DayDevCnt),
                    DayInCome = SqlFunc.AggregateSum(x.DayInCome),
                    DayRegCnt = 0,
                    DayResultCnt = SqlFunc.AggregateSum(x.DayResultCnt),
                    RecordTime = x.RecordTime
                }).ToListAsync();
                var list = query.Adapt<List<ReportChartDto>>();
                return list;
            }
            else
            {
                var tempquery = dbClient.Queryable<YB_DayReport>().Where(x => x.RecordTime >= starttime && x.RecordTime <= endtime);
                var query = await tempquery.OrderBy(x => x.RecordTime, OrderByType.Asc).ToListAsync();
                var list = query.Adapt<List<ReportChartDto>>();
                return list;
            }
        }
    }
}
