using Mall.Model.Extend.Product;
using Mall.Model.Extend.User;
using Mall.Model.Query;
using Mall.Repository.Product;
using Mall.Repository.User;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mall.Module.MarketingCenter
{
    public class StatisticsModule
    {
        private readonly RB_Goods_OrderRepository orderRepository = new RB_Goods_OrderRepository();
        /// <summary>
        /// 返佣
        /// </summary>
        private readonly RB_Goods_OrderCommissionRepository goods_OrderCommissionRepository = new RB_Goods_OrderCommissionRepository();

        /// <summary>
        /// 会员
        /// </summary>
        private readonly RB_Member_UserRepository member_UserRepository = new RB_Member_UserRepository();

        /// <summary>
        /// 分销商
        /// </summary>
        private readonly RB_Distributor_InfoRepository distributor_InfoRepository = new RB_Distributor_InfoRepository();

        /// <summary>
        /// 和平等级
        /// </summary>
        private readonly RB_Distributor_HPGradeInfoRepository distributor_HPGradeInfoRepository = new RB_Distributor_HPGradeInfoRepository();


        /// <summary>
        /// 粉象返佣
        /// </summary>
        private readonly RB_Distributor_FXGradeRepository distributor_FXGradeRepository = new RB_Distributor_FXGradeRepository();

        #region 数据统计-数据概况

        /// <summary>
        /// 损益核算表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<OrderStatistics_Query> GetOrderProfitLossList(int pageIndex, int pageSize, out long count, OrderStatistics_Query dmodel)
        {
            return orderRepository.GetOrderProfitLossList(pageIndex, pageSize, out count, dmodel);
        }



        public List<OrderStatistics_Query> GetAllOrderProfitLossList(OrderStatistics_Query dmodel)
        {
            return orderRepository.GetAllOrderProfitLossList(dmodel);
        }



        /// <summary>
        /// 数据概况
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<DataStatistics_Query> GetOrdertSatistics(DataStatistics_Query dmodel)
        {
            return orderRepository.GetOrdertSatistics(dmodel);
        }


        #region 粉象收益核算
        public List<OrderStatistics_Query> GetFXOrderProfitLossList(int pageIndex, int pageSize, out long count, OrderStatistics_Query dmodel)
        {
            var list = orderRepository.GetFXOrderProfitLossList(pageIndex, pageSize, out count, dmodel);

            if (list != null && list.Any())
            {
                //查询订单的返佣信息
                string orderDetailIds = string.Join(",", list.Select(x => x.Id));
                //分销情况
                var oclist = goods_OrderCommissionRepository.GetListGroupByUser_V2(new RB_Goods_OrderCommission_Extend { TenantId = dmodel.TenantId, MallBaseId = dmodel.MallBaseId, OrderDetailIds = orderDetailIds });

                foreach (var item in list)
                {
                    item.FXCommission = (oclist != null && oclist.Any()) ? oclist.Where(x => x.OrderDetailId == item.Id).Sum(x => (x.Commission ?? 0)) : 0;
                    item.RemitFXCommission = (oclist != null && oclist.Any()) ? oclist.Where(x => x.OrderDetailId == item.Id && x.IsRemit == 1).Sum(x => (x.Commission ?? 0)) : 0;
                }
            }

            return list;
        }
        public List<OrderStatistics_Query> GetFXAllOrderProfitLossList(OrderStatistics_Query dmodel)
        {
            var list = orderRepository.GetFXAllOrderProfitLossList(dmodel);

            if (list != null && list.Any())
            {
                //分销情况
                //分销情况
                var oclist = goods_OrderCommissionRepository.GetListGroupByUser_V2(new RB_Goods_OrderCommission_Extend { TenantId = dmodel.TenantId, MallBaseId = dmodel.MallBaseId, OrderIds = string.Join(",", list.Select(x => x.OrderId)) });
                // var oclist = goods_OrderCommissionRepository.GetListGroupByOrderDetailIds(new RB_Goods_OrderCommission_Extend() { TenantId = dmodel.TenantId, MallBaseId = dmodel.MallBaseId, OrderIds = string.Join(",", list.Select(x => x.OrderId)) });
                if (dmodel.IsSelectOrderCommission == 1)
                {
                    if (oclist.Any())
                    {
                        //获取用户
                        var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = dmodel.TenantId, MallBaseId = dmodel.MallBaseId, UserIds = string.Join(",", oclist.Select(x => x.UserId).Distinct()) });
                        //获取分销商
                        var dislist = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = dmodel.TenantId, MallBaseId = dmodel.MallBaseId, UserIds = string.Join(",", oclist.Select(x => x.UserId).Distinct()) });
                        var HpgradeList = new List<RB_Distributor_HPGradeInfo_Extend>();
                        if (oclist.Where(x => x.Type == 2).Any())
                        {
                            string gradeIds = string.Join(",", oclist.Where(x => x.Type == 2).Select(x => x.Grade).Distinct());
                            HpgradeList = distributor_HPGradeInfoRepository.GetList(new RB_Distributor_HPGradeInfo_Extend() { GradeIds = gradeIds, TenantId = dmodel.TenantId, MallBaseId = dmodel.MallBaseId }, true);
                        }
                        var FXGradeList = new List<RB_Distributor_FXGrade_Extend>();
                        if (oclist.Where(x => x.Type == 3).Any())
                        {
                            string gradeIds = string.Join(",", oclist.Where(x => x.Type == 3).Select(x => x.Grade).Distinct());
                            FXGradeList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { GradeIds = gradeIds, TenantId = dmodel.TenantId, MallBaseId = dmodel.MallBaseId });
                        }
                        foreach (var item in oclist)
                        {
                            var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                            item.UserName = umodel?.Name ?? "";
                            item.Mobile = umodel?.Moblie ?? "";
                            item.Name = dislist.Where(x => x.UserId == item.UserId).FirstOrDefault()?.Name ?? "";
                            if (item.CommissionType == 1 || item.CommissionType == 4)
                            {
                                if (item.Type == 1)
                                {
                                    if (item.Grade == 0)
                                    {
                                        item.GradeDescription = "自购返利";
                                    }
                                    else if (item.Grade == 1)
                                    {
                                        item.GradeDescription = "一级佣金";
                                    }
                                    else if (item.Grade == 2)
                                    {
                                        item.GradeDescription = "二级佣金";
                                    }
                                    else if (item.Grade == 3)
                                    {
                                        item.GradeDescription = "三级佣金";
                                    }
                                }
                                else if (item.Type == 2)
                                {
                                    var hpGModel = HpgradeList.Where(x => x.Id == item.Grade).FirstOrDefault();
                                    item.GradeDescription = hpGModel?.GradeName ?? "暂无等级";
                                }
                                else if (item.Type == 3)
                                {
                                    var fxGModel = FXGradeList.Where(x => x.Id == item.Grade).FirstOrDefault();
                                    item.GradeDescription = fxGModel?.GradeName ?? "暂无等级";
                                }
                            }
                            else if (item.CommissionType == 2)
                            {
                                item.GradeDescription = "供应商返佣";
                            }
                            else if (item.CommissionType == 3)
                            {
                                item.GradeDescription = "微店返佣";
                            }
                        }
                    }
                }
                foreach (var item in list)
                {
                    item.OrderCommissionList = oclist.Where(x => x.OrderDetailId == item.Id).ToList();
                    item.FXCommission = (item.OrderCommissionList != null && item.OrderCommissionList.Any()) ? item.OrderCommissionList.Where(x => x.OrderDetailId == item.Id).Sum(x => (x.Commission ?? 0)) : 0;
                    item.RemitFXCommission = (item.OrderCommissionList != null && item.OrderCommissionList.Any()) ? item.OrderCommissionList.Where(x => x.OrderDetailId == item.Id && x.IsRemit == 1).Sum(x => (x.Commission ?? 0)) : 0;
                }
            }
            return list;
        }


        public List<RB_Goods_OrderCommission_Extend> GetByOrderDetailId(RB_Goods_OrderCommission_Extend model)
        {
            //分销情况
            var oclist = goods_OrderCommissionRepository.GetListGroupByUser_V2(model);
            if (oclist.Any())
            {
                //获取用户
                var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = model.TenantId, MallBaseId = model.MallBaseId, UserIds = string.Join(",", oclist.Select(x => x.UserId).Distinct()) });
                //获取分销商
                var dislist = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = model.TenantId, MallBaseId = model.MallBaseId, UserIds = string.Join(",", oclist.Select(x => x.UserId).Distinct()) });
                var HpgradeList = new List<RB_Distributor_HPGradeInfo_Extend>();
                if (oclist.Where(x => x.Type == 2).Any())
                {
                    string gradeIds = string.Join(",", oclist.Where(x => x.Type == 2 && (x.CommissionType == 1 || x.CommissionType == 4)).Select(x => x.Grade).Distinct());
                    HpgradeList = distributor_HPGradeInfoRepository.GetList(new RB_Distributor_HPGradeInfo_Extend() { GradeIds = gradeIds, TenantId = model.TenantId, MallBaseId = model.MallBaseId }, true);
                }
                var FXGradeList = new List<RB_Distributor_FXGrade_Extend>();
                if (oclist.Where(x => x.Type == 3).Any())
                {
                    string gradeIds = string.Join(",", oclist.Where(x => x.Type == 3 && (x.CommissionType == 1 || x.CommissionType == 4)).Select(x => x.Grade).Distinct());
                    FXGradeList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { GradeIds = gradeIds, TenantId = model.TenantId, MallBaseId = model.MallBaseId });
                }
                foreach (var item in oclist)
                {
                    var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                    item.UserName = umodel?.Name ?? "";
                    item.Mobile = umodel?.Moblie ?? "";
                    item.Name = dislist.Where(x => x.UserId == item.UserId).FirstOrDefault()?.Name ?? "";
                    if (item.CommissionType == 1 || item.CommissionType == 4)
                    {
                        if (item.Type == 1)
                        {
                            if (item.Grade == 0)
                            {
                                item.GradeDescription = "自购返利";
                            }
                            else if (item.Grade == 1)
                            {
                                item.GradeDescription = "一级佣金";
                            }
                            else if (item.Grade == 2)
                            {
                                item.GradeDescription = "二级佣金";
                            }
                            else if (item.Grade == 3)
                            {
                                item.GradeDescription = "三级佣金";
                            }
                        }
                        else if (item.Type == 2)
                        {
                            var hpGModel = HpgradeList.Where(x => x.Id == item.Grade).FirstOrDefault();
                            item.GradeDescription = hpGModel?.GradeName ?? "暂无等级";
                        }
                        else if (item.Type == 3)
                        {
                            var fxGModel = FXGradeList.Where(x => x.Id == item.Grade).FirstOrDefault();
                            item.GradeDescription = fxGModel?.GradeName ?? "暂无等级";
                        }
                    }
                    else if (item.CommissionType == 2)
                    {
                        item.GradeDescription = "供应商返佣";
                    }
                    else if (item.CommissionType == 3)
                    {
                        item.GradeDescription = "微店返佣";
                    }
                }
            }

            return oclist;
        }


        #endregion


        /// <summary>
        /// 获取近一周的数据
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public DataStatistics_Query GetWeeklyOrder(DataStatistics_Query dmodel)
        {
            if (dmodel.IsYesterday == 1)
            {
                dmodel.StartDate = dmodel.EndDate = System.DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
            }
            else
            {
                dmodel.StartDate = System.DateTime.Now.ToString("yyyy-MM-dd");
                dmodel.EndDate = System.DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");
            }
            var List = orderRepository.GetWeeklyOrder(dmodel);

            DataStatistics_Query model = new DataStatistics_Query();
            if (List != null && List.Any())
            {
                model.OrderPay = List.Count();
                model.PayMoney = List.Sum(x => x.Income ?? 0);
                model.PayMemerNum = List.GroupBy(x => x.UserId).Count();
                model.BuyNum = List.Sum(x => x.GoodsTotalNum);
                model.OrderLineList = new List<OrderLine>();
                if (dmodel.IsYesterday == 1)//同一天
                {
                    for (int i = 1; i < 24; i++)
                    {
                        OrderLine modelOrderLine = new OrderLine
                        {
                            OrderPay = List.Where(x => x.CreateDate.Value.ToString("dd") == ((i > 9) ? ("0" + i) : i.ToString())).Count(),
                            PayMoney = List.Where(x => x.CreateDate.Value.ToString("dd") == ((i > 9) ? ("0" + i) : i.ToString())).Sum(x => x.Income ?? 0),
                            PayMemerNum = List.Where(x => x.CreateDate.Value.ToString("dd") == ((i > 9) ? ("0" + i) : i.ToString())).GroupBy(x => x.UserId).Count(),
                            BuyNum = List.Where(x => x.CreateDate.Value.ToString("dd") == ((i > 9) ? ("0" + i) : i.ToString())).Sum(x => x.GoodsTotalNum),
                            DateStr = (i > 9) ? ("0" + i) : i.ToString()
                        };
                        model.OrderLineList.Add(modelOrderLine);
                    }
                }
                else
                {
                    for (int i = 0; i < 7; i++)
                    {
                        OrderLine modelOrderLine = new OrderLine
                        {
                            OrderPay = List.Where(x => x.CreateDate.Value.ToString("yyyy-MM-dd") == System.DateTime.Now.AddDays(i).ToString("yyyy-MM-dd")).Count(),
                            PayMoney = List.Where(x => x.CreateDate.Value.ToString("yyyy-MM-dd") == System.DateTime.Now.AddDays(i).ToString("yyyy-MM-dd")).Sum(x => x.Income ?? 0),
                            PayMemerNum = List.Where(x => x.CreateDate.Value.ToString("yyyy-MM-dd") == System.DateTime.Now.AddDays(i).ToString("yyyy-MM-dd")).GroupBy(x => x.UserId).Count(),
                            BuyNum = List.Where(x => x.CreateDate.Value.ToString("yyyy-MM-dd") == System.DateTime.Now.AddDays(i).ToString("yyyy-MM-dd")).Sum(x => x.GoodsTotalNum),
                            DateStr = System.DateTime.Now.AddDays(i).ToString("yyyy-MM-dd")
                        };
                        model.OrderLineList.Add(modelOrderLine);
                    }
                }
            }
            return model;
        }



        /// <summary>
        /// 商品购买力TOP排行
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<DataStatistics_Query> GetGoosTop(DataStatistics_Query dmodel)
        {
            return orderRepository.GetGoosTop(dmodel);
        }


        /// <summary>
        /// 用户购买力TOP排行
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<DataStatistics_Query> GetMemberTop(DataStatistics_Query dmodel)
        {
            return orderRepository.GetMemberTop(dmodel);
        }

        #endregion


        #region 销售报表
        /// <summary>
        /// 销售统计
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<DataStatistics_Query> GetSellPageList(int pageIndex, int pageSize, out long count, DataStatistics_Query dmodel)
        {
            var list = orderRepository.GetSellPageList(pageIndex, pageSize, out count, dmodel);
            if (dmodel.OrderStatus == 0 || dmodel.OrderStatus == 1 || dmodel.OrderStatus == 2 || dmodel.OrderStatus == 3)
            {
                if (list != null && list.Any())
                {
                    dmodel.RepurchaseNum = 0;
                    dmodel.UserIds = string.Join(",", list.Select(x => x.UserIds));
                    var allOrderList = orderRepository.GetOrderByUserIds(dmodel);
                    foreach (var item in list)
                    {
                        if (!string.IsNullOrWhiteSpace(item.UserIds))
                        {
                            try
                            {
                                DateTime nowTime = Convert.ToDateTime(item.CreateDate + " 23:59:59");
                                var userIdList = item.UserIds.Split(",").Distinct().ToArray();
                                foreach (var itemUserId in userIdList)
                                {
                                    int orderNum = allOrderList.Where(x => x.UserId.ToString() == itemUserId && x.CreateDate <= nowTime).Count();
                                    if (orderNum > 1)
                                    {
                                        item.RepurchaseNum += 1;
                                    }
                                }
                            }
                            catch (Exception)
                            {

                            }
                        }
                    }

                }
            }

            return list;
        }


        /// <summary>
        /// 总成交
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public DataStatistics_Query GetSellOrder(DataStatistics_Query dmodel)
        {

            var List = orderRepository.GetWeeklyOrder(dmodel);

            DataStatistics_Query model = new DataStatistics_Query();
            if (List != null && List.Any())
            {
                model.OrderNum = List.Count();
                model.PayMoney = List.Sum(x => x.Income ?? 0);
                model.PayMemerNum = List.GroupBy(x => x.UserId).Count();
                model.GoodsNum = List.Sum(x => x.GoodsTotalNum);
            }
            return model;
        }


        /// <summary>
        /// 销售统计导出
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<DataStatistics_Query> GetSellExcel(DataStatistics_Query dmodel)
        {
            return orderRepository.GetSellExcel(dmodel);
        }

        #endregion
    }
}
