using Hotline.Orders;
using Hotline.Repository.SqlSugar.DataPermissions;
using Hotline.Repository.SqlSugar.Extensions;
using Hotline.Settings;
using Hotline.Settings.Hotspots;
using Hotline.Share.Requests;
using SqlSugar;
using System.Reflection;
using XF.Domain.Dependency;

namespace Hotline.Repository.SqlSugar.Orders
{
    public class OrderRepository : BaseRepositoryWorkflow<Order>, IOrderRepository, IScopeDependency
    {
        private readonly IDataPermissionFilterBuilder _dataPermissionFilterBuilder;

        public OrderRepository(ISugarUnitOfWork<HotlineDbContext> uow,
            IDataPermissionFilterBuilder dataPermissionFilterBuilder
            ) : base(uow, dataPermissionFilterBuilder)
        {
            _dataPermissionFilterBuilder = dataPermissionFilterBuilder;
        }

        public async Task<string> AddOrderNavAsync(Order order, CancellationToken cancellationToken)
        {
            //弥补AddNav方法没有自动指派到创建人
            order.AssignToCreator(_dataPermissionFilterBuilder.DataPermissionManager);

            await AddNav(order).Include(d => d.OrderExtension).ExecuteCommandAsync();

            return order.Id;
        }



        /// <summary>
        /// 工单词库批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task RemoveOrderWrodBatchAsync(List<string> ids, CancellationToken cancellationToken)
        {
            await Db.Deleteable<OrderWord>().In(x => x.Id, ids).ExecuteCommandAsync(cancellationToken);
        }


        /// <summary>
        /// 工单观察批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task RemoveOrderObserveBatchAsync(List<string> ids, CancellationToken cancellationToken)
        {
            await Db.Deleteable<OrderObserve>().In(x => x.Id, ids).ExecuteCommandAsync(cancellationToken);
        }

        /// <summary>
        /// 工单终结批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task RemoveOrderFinalityBatchAsync(List<string> ids, CancellationToken cancellationToken)
        {
            await Db.Deleteable<OrderFinality>().In(x => x.Id, ids).ExecuteCommandAsync(cancellationToken);
        }

        public async Task OrderScreenRevisionVisit(string VisitId, bool canHandle, CancellationToken cancellationToken)
        {

            await Db.Updateable<OrderVisit>().SetColumns(x => x.IsCanHandle == canHandle).Where(x => x.Id == VisitId).ExecuteCommandAsync(cancellationToken);
        }

        public async Task FileAsync(Order order, CancellationToken cancellationToken)
        {
            await Db.Updateable<Order>().SetColumns(x => x.FileJson == order.FileJson).Where(x => x.Id == order.Id).ExecuteCommandAsync(cancellationToken);
        }

        private static object GetPropertyValue(object obj, string property)
        {
            PropertyInfo propertyInfo = obj.GetType().GetProperty(property);
            return propertyInfo.GetValue(obj, null);
        }

        public async Task<object> HotPortJoinOrgStatistics(DateTime StartTime, DateTime EndTime, bool IsCenter, string? OrgCode)
        {
            //查询一级热点
            var hotSpotList = await Db.Queryable<Hotspot>().Where(x => string.IsNullOrEmpty(x.ParentId)).ToListAsync();
            List<dynamic>? listReturn = new List<dynamic>();
            foreach (var item in hotSpotList)
            {
                var table = await Db.Queryable<Order>()
                    .LeftJoin<SystemOrganize>((it, o) => it.ActualHandleOrgCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6")) == o.Id)
                    .Where((it, o) => it.CreationTime >= StartTime && it.CreationTime <= EndTime)
                    .WhereIF(IsCenter == false, (it, o) => o.Id.StartsWith(OrgCode))
                    .GroupBy((it, o) => new
                    {
                        CurrentHandleOrgCode = (it.ActualHandleOrgCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6"))),
                        o.Name
                    })
                    .Select((it, o) => new
                    {
                        OrgCode = it.ActualHandleOrgCode.Substring(SqlFunc.MappingColumn<int>("0"), SqlFunc.MappingColumn<int>("6")),
                        Count = SqlFunc.AggregateSum(SqlFunc.IIF(it.HotspotId.Substring(0, 2) == item.Id, 1, 0)),
                        Key = item.Id,
                        OrgName = o.Name,
                        HotSorpName = item.HotSpotName
                    }).ToPivotListAsync(x => x.Key, x => new { x.OrgCode, x.OrgName, x.HotSorpName }, x => x.Sum(x => x.Count));
                listReturn.AddRange(table);
            }
            return new { HotSpot = hotSpotList, Data = listReturn };
        }

        public ISugarQueryable<DepartmentalProcessingStatisticsDataDto> OrderUnionAll(ISugarQueryable<DepartmentalProcessingStatisticsDataDto> t1,
            ISugarQueryable<DepartmentalProcessingStatisticsDataDto> t2,
            ISugarQueryable<DepartmentalProcessingStatisticsDataDto> t3,
            ISugarQueryable<DepartmentalProcessingStatisticsDataDto> t4,
            ISugarQueryable<DepartmentalProcessingStatisticsDataDto> t5,
            ISugarQueryable<DepartmentalProcessingStatisticsDataDto> t6)
        {
            return Db.UnionAll(t1, t2, t3, t4, t5, t6)
                       .GroupBy(p => new { p.OrgCode })
                       .Select(p => new DepartmentalProcessingStatisticsDataDto
                       {
                           OrgCode = p.OrgCode,
                         //  OrderCountNum = SqlFunc.AggregateSum(p.OrderCountNum),
                           YBOrderCountNum = SqlFunc.AggregateSum(p.YBOrderCountNum),
                           ZBOrderCountNum = SqlFunc.AggregateSum(p.ZBOrderCountNum),
                           Archived = SqlFunc.AggregateSum(p.Archived),
                           ToBeArchived = SqlFunc.AggregateSum(p.ToBeArchived),
                           WaitPublished = SqlFunc.AggregateSum(p.WaitPublished),
                           PublishedOpen = SqlFunc.AggregateSum(p.PublishedOpen),
                           PublishedNoOpen = SqlFunc.AggregateSum(p.PublishedNoOpen),
                           YBOverdue = SqlFunc.AggregateSum(p.YBOverdue),
                           ZBOverdue = SqlFunc.AggregateSum(p.ZBOverdue),
                           CompleteOnTime= SqlFunc.AggregateSum(p.CompleteOnTime),
                           HQYBOverdue = SqlFunc.AggregateSum(p.HQYBOverdue),
                           HQZBOverdue = SqlFunc.AggregateSum(p.HQZBOverdue),
                           DelayEnd = SqlFunc.AggregateSum(p.DelayEnd),
                           DelayWait = SqlFunc.AggregateSum(p.DelayWait),
                           OrderDelayCount = SqlFunc.AggregateSum(p.OrderDelayCount),
                           ScreenCount = SqlFunc.AggregateSum(p.ScreenCount),
                           ScreenApproval = SqlFunc.AggregateSum(p.ScreenApproval),
                           ScreenPass = SqlFunc.AggregateSum(p.ScreenPass),
                           ScreenNotPass = SqlFunc.AggregateSum(p.ScreenNotPass),
                           SatisfactionCount = SqlFunc.AggregateSum(p.SatisfactionCount),
                           NotSatisfactionCount = SqlFunc.AggregateSum(p.NotSatisfactionCount)
                       })
                       .MergeTable();

                      
        }

        public ISugarQueryable<SelectOrderId> OrderListUnionAll(ISugarQueryable<SelectOrderId> t1, ISugarQueryable<SelectOrderId> t2)
        {
            return Db.UnionAll(t1, t2).Select(it => new SelectOrderId { Id = it.Id }).MergeTable();
        }
    }

    public class OrderScreenRepository : BaseRepositoryWorkflow<OrderScreen>, IOrderScreenRepository, IScopeDependency
    {
        public OrderScreenRepository(ISugarUnitOfWork<HotlineDbContext> uow, IDataPermissionFilterBuilder dataPermissionFilterBuilder) : base(uow, dataPermissionFilterBuilder)
        {
        }
    }

    public class OrderDelayRepository : BaseRepositoryWorkflow<OrderDelay>, IOrderDelayRepository, IScopeDependency
    {
        public OrderDelayRepository(ISugarUnitOfWork<HotlineDbContext> uow, IDataPermissionFilterBuilder dataPermissionFilterBuilder) : base(uow, dataPermissionFilterBuilder)
        {
        }
    }

}
