using Mall.Common.Plugin;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.User;
using Mall.Repository.Customer;
using Mall.Repository.Product;
using Mall.Repository.User;
using System;
using System.Collections.Generic;
using System.Linq;
using VT.FW.DB;

namespace Mall.Module.User
{
    /// <summary>
    /// 用户管理
    /// </summary>
    public class MemberUserModule
    {
        /// <summary>
        /// 用户管理
        /// </summary>
        private readonly RB_Member_UserRepository member_UserRepository = new RB_Member_UserRepository();
        /// <summary>
        /// 管理消息提醒
        /// </summary>
        private readonly RB_Message_NoticeRepository message_NoticeRepository = new RB_Message_NoticeRepository();
        /// <summary>
        /// 订单商品
        /// </summary>
        private readonly RB_Goods_OrderDetailRepository goods_OrderDetailRepository = new RB_Goods_OrderDetailRepository();
        /// <summary>
        /// 售后订单
        /// </summary>
        private readonly RB_Goods_OrderAfterSaleRepository goods_OrderAfterSaleRepository = new RB_Goods_OrderAfterSaleRepository();
        /// <summary>
        /// 同业客户积分
        /// </summary>
        private readonly RB_Customer_IntegralRepository customer_IntegralRepository = new RB_Customer_IntegralRepository();
        /// <summary>
        /// 会员积分
        /// </summary>
        private readonly RB_Member_IntegralRepository member_IntegralRepository = new RB_Member_IntegralRepository();
        /// <summary>
        /// 分销商
        /// </summary>
        private readonly RB_Distributor_InfoRepository distributor_InfoRepository = new RB_Distributor_InfoRepository();
        /// <summary>
        /// 分销商日志
        /// </summary>
        private readonly RB_Distributor_LogRepository distributor_LogRepository = new RB_Distributor_LogRepository();


        /// <summary>
        /// 根据用户Id更新用户头像和名称
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool SetMemberUserNameAndPhoto(RB_Member_User_Extend extModel)
        {
            // HK 2024-12-16 注释,没有开通微信 获取昵称和头像接口
            //Dictionary<string, object> fileds = new Dictionary<string, object>()
            //{
            //    { nameof(RB_Member_User_Extend.Name),extModel.AliasName},
            //    { nameof(RB_Member_User_Extend.Photo),extModel.Photo},
            //};
            //return member_UserRepository.Update(fileds, new WhereHelper(nameof(RB_Member_User_Extend.Id), extModel.Id));
            return true;
        }


        public bool SetMemberUserPhoneNum(RB_Member_User_Extend extModel)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_Member_User_Extend.PhoneNum),extModel.PhoneNum},
            };
            return member_UserRepository.Update(fileds, new WhereHelper(nameof(RB_Member_User_Extend.Id), extModel.Id));
        }

        /// <summary>
        /// 绑定同业
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool SetMemberBindCustomer(RB_Member_User_Extend extModel) {

            var userModel = member_UserRepository.GetEntity(extModel.Id);
            if (userModel == null || userModel.CustomerId > 0) { return true; }

            //根据OpenID 反查询 CustomerId
            var CustomerModel = customer_IntegralRepository.GetCustomerToOpenId(extModel.CustomerOpenId);
            if (CustomerModel == null) { return false; }
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_Member_User_Extend.CustomerId),CustomerModel.CustomerId},
                { nameof(RB_Member_User_Extend.CustomerChildrenId),CustomerModel.CustomerChildrenId},
            };
            bool flag = member_UserRepository.Update(fileds, new WhereHelper(nameof(RB_Member_User_Extend.Id), extModel.Id));
            if (flag) {
                var distModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = userModel.Id }).FirstOrDefault();
                if (distModel != null) {
                    if (distModel.FXGradeId <= 2) {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Distributor_Info_Extend.FXGradeId),3},
                            { nameof(RB_Distributor_Info_Extend.UpdateDate),DateTime.Now}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Distributor_Info_Extend.Id),
                                  FiledValue=distModel.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        bool flag2 = distributor_InfoRepository.Update(keyValues, wheres);
                        if (flag2)
                        {
                            //记录日志
                            distributor_LogRepository.Insert(new Model.Entity.User.RB_Distributor_Log()
                            {
                                Content = "同行绑定赞羊，初始化分销商等级为：旅享家",
                                CreateDate = DateTime.Now,
                                EmpId = 0,
                                Id = 0,
                                MallBaseId = 1,
                                TenantId = 1,
                                Type = 1,
                                UserId = userModel.Id
                            });
                        }
                    }
                }
            }
            //因为存在 一个同行 下有多个 联系人的情况，
            //if (flag) {
            //    //开始初始化 积分数据
            //    var list = customer_IntegralRepository.GetList(new Model.Extend.Customer.RB_Customer_Integral_Extend() { OrderType = 1, CustomerId = CustomerId });
            //    if (list.Any())
            //    {
            //        foreach (var item in list)
            //        {
            //            member_IntegralRepository.Insert(new Model.Entity.User.RB_Member_Integral()
            //            {
            //                Id = 0,
            //                Image = 0,
            //                Type = item.IntegralNum > 0 ? Common.Enum.MarketingCenter.RecordTypeEnum.Income : Common.Enum.MarketingCenter.RecordTypeEnum.Expend,
            //                Integral = Math.Abs(Convert.ToInt32(item.IntegralNum)),
            //                CreateDate = item.CreateTime,
            //                MallBaseId = extModel.MallBaseId,
            //                TenantId = extModel.TenantId,
            //                OrderId = item.OrderId,
            //                PlatformType = Common.Enum.User.UserSourceEnum.ERP,
            //                UserId = extModel.Id,
            //                Description = item.Description,
            //                Remarks = ""
            //            });
            //        }
            //        Dictionary<string, object> fileds2 = new Dictionary<string, object>()
            //        {
            //            { nameof(RB_Member_User_Extend.Integral),list.Sum(x=>x.IntegralNum)},
            //        };
            //        member_UserRepository.Update(fileds, new WhereHelper(nameof(RB_Member_User_Extend.Id), extModel.Id));
            //    }
            //}
            return flag;
        }

        #region 小程序管理端-消息提醒

        /// <summary>
        /// 获取消息提醒分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Message_Notice_Extend> GetAdminMessageNoticePageList(int pageIndex, int pageSize, out long count, RB_Message_Notice_Extend demodel)
        {
            var list = message_NoticeRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any()) {
                string userIds = string.Join(",", list.Select(x => x.UserId).Distinct());
                var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { MallBaseId = demodel.MallBaseId, UserIds = userIds });
                List<RB_Goods_OrderDetail_Extend> odlist = new List<RB_Goods_OrderDetail_Extend>();
                if (demodel.Type == 1 || demodel.Type == 2)
                {
                    //下单    取消订单退款
                    //查询订单 + 订单商品
                    string orderIds = string.Join(",", list.Select(x => x.SourceId));
                    odlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderIds = orderIds });
                    foreach (var item in list) {
                        var od2list = odlist.Where(x => x.OrderId == item.SourceId).ToList();
                        item.GoodsName = (od2list.FirstOrDefault()?.GoodsName ?? "") + (od2list.Count() > 1 ? ("等" + od2list.Count() + "件商品") : "");
                        item.GoodsCoverImage = od2list.FirstOrDefault()?.CoverImage ?? "";
                        if (item.Type == 1)
                        {
                            item.OrderTypeName = od2list.FirstOrDefault()?.OrderType.GetEnumName();
                        }
                        var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                        item.UserName = umodel?.Name ?? "";
                    }
                }
                else if (demodel.Type == 3) {
                    //售后  查询售后订单
                    string orderIds = string.Join(",", list.Select(x => x.SourceId));
                    var aslist = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, AfterSaleIds = orderIds });
                    if (aslist.Any()) {
                        string odIds = string.Join(",", aslist.Select(x => x.OrderDetialId));
                        var od3list = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderDetailIds = odIds });
                        foreach (var item in list)
                        {
                            var asmodel = aslist.Where(x => x.ReOrderId == item.SourceId).FirstOrDefault();
                            var odmodel = od3list.Where(x => x.Id == (asmodel?.OrderDetialId ?? 0)).FirstOrDefault();
                            item.GoodsName = odmodel?.GoodsName ?? "";
                            item.GoodsCoverImage = odmodel?.CoverImage ?? "";
                            var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                            item.UserName = umodel?.Name ?? "";
                        }
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取管理端信息数量
        /// </summary>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public object GetAdminMessageNoticeNum(int tenantId, int mallBaseId)
        {
            var list = message_NoticeRepository.GetAdminMessageNoticeNum(tenantId, mallBaseId);
            return new
            {
                OrderNum = list.Where(x => x.Type == 1).FirstOrDefault()?.IsLook ?? 0,
                CancelNum = list.Where(x => x.Type == 2).FirstOrDefault()?.IsLook ?? 0,
                AfterSaleNum = list.Where(x => x.Type == 3).FirstOrDefault()?.IsLook ?? 0,
                TotalNum = list.Sum(x => x.IsLook)
            };
        }

        /// <summary>
        /// 设置消息已读
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetAdminMessageLook(RB_Message_Notice_Extend demodel)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Message_Notice_Extend.IsLook), 1}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() { 
                new WhereHelper(){ 
                     FiledName = nameof(RB_Message_Notice_Extend.TenantId),
                      FiledValue = demodel.TenantId,
                       OperatorEnum= OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName = nameof(RB_Message_Notice_Extend.MallBaseId),
                      FiledValue = demodel.MallBaseId,
                       OperatorEnum= OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName = nameof(RB_Message_Notice_Extend.IsLook),
                      FiledValue = 2,
                       OperatorEnum= OperatorEnum.Equal
                }
            };
            if (demodel.Id > 0)
            {
                //修改单条数据已读
                wheres.Add(new WhereHelper()
                {
                    FiledName = nameof(RB_Message_Notice_Extend.Id),
                    FiledValue = demodel.Id,
                    OperatorEnum = OperatorEnum.Equal
                });
            }
            else if (demodel.Type > 0) {
                //根据类型修改
                wheres.Add(new WhereHelper()
                {
                    FiledName = nameof(RB_Message_Notice_Extend.Type),
                    FiledValue = demodel.Type,
                    OperatorEnum = OperatorEnum.Equal
                });
            }
            bool flag = message_NoticeRepository.Update(keyValues, wheres);
            return flag ? "" : "出错了，请联系管理员";
        }
        #endregion
    }
}
