using Mall.Model.Extend.TradePavilion;
using Mall.Model.Extend.User;
using Mall.Repository.Point;
using Mall.Repository.TradePavilion;
using Mall.Repository.User;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using VT.FW.DB;
using Mall.Repository.Miai;
using Mall.Common.Enum;
using Mall.Common.Plugin;

namespace Mall.Module.TradePavilion
{
    /// <summary>
    /// 商会活动报名处理类
    /// </summary>
    public class CommerceConsultModule
    {
        /// <summary>
        /// 商会活动报名仓储层对象
        /// </summary>
        private readonly RB_Commerce_ConsultRepository consultRepository = new RB_Commerce_ConsultRepository();
        /// <summary>
        /// 活动
        /// </summary>
        private readonly RB_Commerce_ActivityRepository commerce_ActivityRepository = new RB_Commerce_ActivityRepository();
        /// <summary>
        /// 点数记录表
        /// </summary>
        private readonly RB_Member_PointBalanceRepository member_PointBalanceRepository = new RB_Member_PointBalanceRepository();
        /// <summary>
        /// 用户
        /// </summary>
        private readonly RB_Member_UserRepository member_UserRepository = new RB_Member_UserRepository();
        /// <summary>
        /// 相亲消息
        /// </summary>
        private readonly RB_Miai_MessageRepository miai_MessageRepository = new RB_Miai_MessageRepository();

        /// <summary>
        /// 公司认证
        /// </summary>
        private readonly RB_CompanyRepository companyRepository = new RB_CompanyRepository();

        /// <summary>
        /// 品牌申请
        /// </summary>
        private readonly RB_BrandApplyForRepository brandApplyForRepository = new RB_BrandApplyForRepository();
        /// <summary>
        /// 载体申请
        /// </summary>
        private readonly RB_CarrierApplyForRepository carrierApplyForRepository = new RB_CarrierApplyForRepository();

        /// <summary>
        /// 获取商会活动报名分页列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<ActivityUserItem> GetCommerceConsultPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Commerce_Consult_Extend query)
        {
            List<ActivityUserItem> result = new List<ActivityUserItem>();
            var list = consultRepository.GetCommerceConsultStatisticsPageRepository(pageIndex, pageSize, out rowsCount, query);
            if (list != null && list.Count > 0)
            {
                string userids = string.Join(",", list.Select(qitem => qitem.UserId));
                string activityIds = string.Join(",", list.Select(qitem => qitem.ActivityId));
                var authList = companyRepository.GetCompanyListRepository(new RB_Company_Extend() { UserIds = userids });
                var memberList = member_UserRepository.GetList(new RB_Member_User_Extend()
                {
                    UserIds = userids
                });
                var userList = list.GroupBy(qitem => new { qitem.UserId, qitem.ActivityId }).Select(qitem => new { qitem.Key.UserId, qitem.Key.ActivityId });
                var subList = consultRepository.GetCommerceConsultListRepository(new RB_Commerce_Consult_Extend()
                {
                    QActivityIds = activityIds,
                    QUserIds = userids,
                });
                foreach (var item in userList)
                {
                    var userModel = memberList?.Where(qitem => qitem.Id == item.UserId)?.FirstOrDefault();
                    var authModel = authList?.Where(qitem => qitem.CreateBy == item.UserId)?.FirstOrDefault();
                    string CompanyStatus = "未认证";
                    string FirstShopTypeName = "";
                    string AuthName = "";
                    if (authModel!=null)
                    {
                        if (authModel.CompanyStatus == 0)
                        {
                            CompanyStatus = "待审核";
                        }
                        else if (authModel.CompanyStatus == 1)
                        {
                            CompanyStatus = "审核通过";
                        }
                        else if (authModel.CompanyStatus == 2)
                        {
                            CompanyStatus = "审核拒绝";
                        }

                        //品牌
                        if (authModel.FirstShopType == 1)
                        {
                            var brandList = brandApplyForRepository.GetBrandListByWhere(new RB_BrandApplyFor_Extend {   CompanyId = authModel.CompanyId });
                            FirstShopTypeName = "认证品牌";
                            AuthName = brandList?.FirstOrDefault()?.BrandName ?? "";
                        }
                        //载体
                        else if (authModel.FirstShopType == 2)
                        {
                            var carrierList = carrierApplyForRepository.GetCarrierList(new RB_CarrierApplyFor_Extend() {   CompanyId = authModel.CompanyId });
                            FirstShopTypeName = "认证载体";
                            AuthName = carrierList?.FirstOrDefault()?.CarrierName ?? "";
                        }
                    }
                    ActivityUserItem activity = new ActivityUserItem()
                    {
                        UserId = item.UserId,
                        UserName = userModel?.Name ?? "",
                        CompanyStatusStr = CompanyStatus,
                        CompanyName = authModel?.CompanyName ?? "",
                        FirstShopTypeName = FirstShopTypeName,
                        AuthName = AuthName,
                        RowSpan=0,
                        SignUserList = new List<SignUserItem>(),
                    };
                    var tempList = subList?.Where(qitem => qitem.UserId == item.UserId && qitem.ActivityId == item.ActivityId)?.ToList();
                    if (tempList != null && tempList.Count > 0)
                    {
                        foreach (var sItem in tempList)
                        {
                            SignUserItem signUser = new SignUserItem()
                            {
                                Id = sItem.Id,
                                ActivityId = sItem.ActivityId,
                                LinkMan = sItem.LinkMan,
                                LinkTel = sItem.LinkTel,
                                Post = sItem.Post,
                                CountryInfo = sItem.CountryInfo,
                                CompanyName = sItem.CompanyName,
                                Nature = sItem.Nature.GetEnumName()
                            };
                            activity.SignUserList.Add(signUser);
                        }
                        activity.RowSpan = tempList.Count > 1 ? tempList.Count : 0;
                    }
                    result.Add(activity);
                }
            };
            return result;
        }

        /// <summary>
        /// 获取商会活动报名列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Commerce_Consult_Extend> GetCommerceConsultListModule(RB_Commerce_Consult_Extend query)
        {
            return consultRepository.GetCommerceConsultListRepository(query);
        }

        /// <summary>
        /// 新增修改商会活动报名
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string SetCommerceConsultModule(RB_Commerce_Consult_Extend model)
        {
            var umodel = member_UserRepository.GetEntity(model.UserId);
            bool flag;
            if (model.Id > 0)
            {
                var oldModel = consultRepository.GetEntity(model.Id);
                if (oldModel.Money != model.Money)
                {
                    if (umodel.PointNum + oldModel.Money < model.Money)
                    {
                        return "您的星星值不足，请充值后再试";
                    }
                }
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Commerce_Consult_Extend.ActivityId),model.ActivityId },
                    {nameof(RB_Commerce_Consult_Extend.UserId),model.UserId },
                    {nameof(RB_Commerce_Consult_Extend.LinkMan),model.LinkMan },
                    {nameof(RB_Commerce_Consult_Extend.LinkTel),model.LinkTel },
                    {nameof(RB_Commerce_Consult_Extend.PeopleNum),model.PeopleNum },
                    {nameof(RB_Commerce_Consult_Extend.Money),model.Money },
                    {nameof(RB_Commerce_Consult_Extend.Remark),model.Remark }
                };
                flag = consultRepository.Update(fileds, new WhereHelper(nameof(RB_Commerce_Consult_Extend.Id), model.Id));
                if (flag)
                {
                    if (oldModel.Money != model.Money)
                    {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() 
                        {
                            { nameof(RB_Member_User_Extend.PointNum),umodel.PointNum + oldModel.Money - model.Money}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() 
                        {
                            new WhereHelper()
                            {
                                 FiledName=nameof(RB_Member_User_Extend.Id),
                                 FiledValue=umodel.Id,
                                 OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        member_UserRepository.Update(keyValues, wheres);
                        int diff = model.Money - oldModel.Money;
                        string Remarks;
                        if (diff > 0)
                        {
                            Remarks = "修改活动报名人数，增加使用点数：" + diff;
                        }
                        else
                        {
                            Remarks = "修改活动报名人数，退回使用点数：" + (0 - diff);
                        }
                        member_PointBalanceRepository.Insert(new Model.Entity.User.RB_Member_PointBalance()
                        {
                            Id = 0,
                            UserId = umodel.Id,
                            Type = Common.Enum.MarketingCenter.RecordTypeEnum.Expend,
                            TenantId = umodel.TenantId,
                            OrderId = 0,
                            PlatformType = Common.Enum.User.UserSourceEnum.WeiXin,
                            MallBaseId = umodel.MallBaseId,
                            PonitNum = diff,
                            CreateDate = DateTime.Now,
                            Description = Remarks,
                            Remarks = Remarks
                        });
                    }
                }
            }
            else
            {
                if (model.Money > 0)
                {
                    if (umodel.PointNum < model.Money)
                    {
                        return "您的星星值不足，请充值后再试";
                    }
                    var actModel = commerce_ActivityRepository.GetEntity(model.ActivityId);
                    if (actModel == null) { return "活动不存在"; }
                    if (model.UnitPrice != actModel.Price) { return "单价有误"; }
                    if (model.Money != model.UnitPrice * model.PeopleNum) { return "总价计算有误"; }
                }
                var newId = consultRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
                if (flag)
                {
                    if (model.Money > 0)
                    {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() 
                        {
                            { nameof(RB_Member_User_Extend.PointNum),umodel.PointNum - model.Money}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>()
                        {
                            new WhereHelper()
                            {
                                 FiledName=nameof(RB_Member_User_Extend.Id),
                                 FiledValue=umodel.Id,
                                 OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        member_UserRepository.Update(keyValues, wheres);
                        member_PointBalanceRepository.Insert(new Model.Entity.User.RB_Member_PointBalance()
                        {
                            Id = 0,
                            UserId = umodel.Id,
                            Type = Common.Enum.MarketingCenter.RecordTypeEnum.Expend,
                            TenantId = umodel.TenantId,
                            OrderId = 0,
                            PlatformType = Common.Enum.User.UserSourceEnum.WeiXin,
                            MallBaseId = umodel.MallBaseId,
                            PonitNum = model.Money,
                            CreateDate = DateTime.Now,
                            Description = "活动报名，使用点数：" + model.Money,
                            Remarks = "活动报名，使用点数：" + model.Money,
                        });
                    }
                }
            }
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 活动报名
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetBatchActivityEnrollInfo(List<RB_Commerce_Consult_Extend> list)
        {
            bool flag = false;
            try
            {
                var trans = consultRepository.DbTransaction;
                foreach (var demodel in list)
                {
                    flag = consultRepository.Insert(demodel, trans) > 0;
                }
                consultRepository.DBSession.Commit();
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "SetBatchActivityEnrollInfo");
                consultRepository.DBSession.Rollback("SetBatchActivityEnrollInfo");
            }
            return flag;
        }

        /// <summary>
        /// 根据编号获取商会活动报名实体
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Commerce_Consult_Extend GetCommerceConsultModule(object Id)
        {
            return consultRepository.GetEntity<RB_Commerce_Consult_Extend>(Id);
        }

        /// <summary>
        /// 删除首店报名人员
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool RemoveTrdceConsultModule(int Id)
        {
            //Dictionary<string, object> fileds = new Dictionary<string, object>()
            //{
            //    {nameof(RB_Commerce_Consult_Extend.Status),(int)DateStateEnum.Delete },
            //};
            bool flag = consultRepository.DeleteOne(new WhereHelper(nameof(RB_Commerce_Consult_Extend.Id), Id));
            //  consultRepository.Update(fileds, new WhereHelper(nameof(RB_Commerce_Consult_Extend.Id), Id));
            return flag;
        }

        /// <summary>
        /// 新增修改首店报名人员
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetTradeConsultModule(RB_Commerce_Consult_Extend model)
        {
            bool flag = false;
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Commerce_Consult_Extend.LinkMan),model.LinkMan },
                    {nameof(RB_Commerce_Consult_Extend.LinkTel),model.LinkTel },
                    {nameof(RB_Commerce_Consult_Extend.Post),model.Post },
                    {nameof(RB_Commerce_Consult_Extend.CountryInfo),model.CountryInfo },
                };
                flag = consultRepository.Update(fileds, new WhereHelper(nameof(RB_Commerce_Consult_Extend.Id), model.Id));
            }
            else
            {
                var newId = consultRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 更新商会活动报名状态
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        public bool RemoveCommerceConsultModule(int Id, int Status)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Commerce_Consult_Extend.Status),Status },
            };
            bool flag = consultRepository.Update(fileds, new WhereHelper(nameof(RB_Commerce_Consult_Extend.Id), Id));
            if (flag)
            {
                var model = consultRepository.GetEntity(Id);
                miai_MessageRepository.Insert(new Model.Extend.Miai.RB_Miai_Message_Extend()
                {
                    Id = 0,
                    Type = Common.Enum.MiAi.MessageTypeEnum.ActivityCancel,
                    UserId = 0,
                    SourceId = model.ActivityId,
                    Content = "取消用户活动报名",
                    Status = 0,
                    TenantId = model.TenantId,
                    MallBaseId = model.MallBaseId,
                    CreateBy = 0,
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now
                });
            }
            return flag;
        }

        /// <summary>
        /// 取消商会活动报名状态
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        public bool CancelCommerceConsultModule(int activityId, string cancelRemark, out int IsCancelConfirm, int userId)
        {
            bool flag;
            var amodel = commerce_ActivityRepository.GetEntity(activityId);
            IsCancelConfirm = amodel.IsCancelConfirm;
            var cmodel = consultRepository.GetCommerceConsultListRepository(new RB_Commerce_Consult_Extend() { ActivityId = activityId, UserId = userId }).FirstOrDefault();
            if (cmodel == null || cmodel.Status == Common.Enum.DateStateEnum.Delete) { return true; }
            if (amodel.IsCancelConfirm == 1)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Commerce_Consult_Extend.IsApplyForCancel),1 },
                    {nameof(RB_Commerce_Consult_Extend.CancelRemark),cancelRemark },
                };
                List<WhereHelper> list = new List<WhereHelper>()
                {
                    new WhereHelper(nameof(RB_Commerce_Consult_Extend.Id), cmodel.Id)
                };
                flag = consultRepository.Update(fileds, list);
            }
            else
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Commerce_Consult_Extend.Status),1 },
                };
                List<WhereHelper> list = new List<WhereHelper>()
                {
                    new WhereHelper(nameof(RB_Commerce_Consult_Extend.ActivityId), activityId),
                    new WhereHelper(nameof(RB_Commerce_Consult_Extend.UserId), userId),
                };
                flag = consultRepository.Update(fileds, list);
                if (flag && cmodel.Money > 0)
                {
                    //取消退回使用点数
                    var umodel = member_UserRepository.GetEntity(cmodel.UserId);
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() 
                    {
                        { nameof(RB_Member_User_Extend.PointNum),umodel.PointNum + cmodel.Money}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() 
                    {
                        new WhereHelper()
                        {
                            FiledName=nameof(RB_Member_User_Extend.Id),
                            FiledValue=umodel.Id,
                            OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    member_UserRepository.Update(keyValues, wheres);
                    member_PointBalanceRepository.Insert(new Model.Entity.User.RB_Member_PointBalance()
                    {
                        Id = 0,
                        UserId = umodel.Id,
                        Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                        TenantId = umodel.TenantId,
                        OrderId = 0,
                        PlatformType = Common.Enum.User.UserSourceEnum.WeiXin,
                        MallBaseId = umodel.MallBaseId,
                        PonitNum = cmodel.Money,
                        CreateDate = DateTime.Now,
                        Description = "取消活动报名，退回使用星星：" + cmodel.Money,
                        Remarks = "取消活动报名，退回使用星星：" + cmodel.Money,
                    });
                }
                if (flag)
                {
                    miai_MessageRepository.Insert(new Model.Extend.Miai.RB_Miai_Message_Extend()
                    {
                        Id = 0,
                        Type = Common.Enum.MiAi.MessageTypeEnum.ActivityCancel,
                        UserId = userId,
                        SourceId = activityId,
                        Content = "用户取消活动报名",
                        Status = 0,
                        TenantId = amodel.TenantId,
                        MallBaseId = amodel.MallBaseId,
                        CreateBy = userId,
                        CreateDate = DateTime.Now,
                        UpdateDate = DateTime.Now
                    });
                }
            }
            return flag;
        }

        /// <summary>
        /// 客人申请取消
        /// </summary>
        /// <param name="id"></param>
        /// <param name="applyForCancelStatus"></param>
        /// <param name="rejectRemark"></param>
        /// <returns></returns>
        public bool SetCommerceConsultApplyCancel(int id, int applyForCancelStatus, string rejectRemark)
        {
            var model = consultRepository.GetEntity(id);
            if (model == null || model.Status == Common.Enum.DateStateEnum.Delete) { return false; }
            int Status = 0;
            if (applyForCancelStatus == 1)
            {
                Status = 1;
            }
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Commerce_Consult_Extend.Status),Status },
                {nameof(RB_Commerce_Consult_Extend.ApplyForCancelStatus),applyForCancelStatus },
                {nameof(RB_Commerce_Consult_Extend.RejectRemark),rejectRemark },
            };
            List<WhereHelper> list = new List<WhereHelper>()
            {
                new WhereHelper(nameof(RB_Commerce_Consult_Extend.Id), id),
            };
            bool flag = consultRepository.Update(fileds, list);
            if (flag)
            {
                if (model.Money > 0)
                {
                    var umodel = member_UserRepository.GetEntity(model.UserId);
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Member_User_Extend.PointNum),umodel.PointNum + model.Money}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                                FiledName=nameof(RB_Member_User_Extend.Id),
                                FiledValue=umodel.Id,
                                OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    member_UserRepository.Update(keyValues, wheres);
                    member_PointBalanceRepository.Insert(new Model.Entity.User.RB_Member_PointBalance()
                    {
                        Id = 0,
                        UserId = umodel.Id,
                        Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                        TenantId = umodel.TenantId,
                        OrderId = 0,
                        PlatformType = Common.Enum.User.UserSourceEnum.WeiXin,
                        MallBaseId = umodel.MallBaseId,
                        PonitNum = model.Money,
                        CreateDate = DateTime.Now,
                        Description = "取消活动报名，退回使用星星：" + model.Money,
                        Remarks = "取消活动报名，退回使用星星：" + model.Money,
                    });
                }
                if (Status == 1)
                {
                    miai_MessageRepository.Insert(new Model.Extend.Miai.RB_Miai_Message_Extend()
                    {
                        Id = 0,
                        Type = Common.Enum.MiAi.MessageTypeEnum.ActivityCancel,
                        UserId = model.UserId,
                        SourceId = model.ActivityId,
                        Content = "同意取消活动报名",
                        Status = 0,
                        TenantId = model.TenantId,
                        MallBaseId = model.MallBaseId,
                        CreateBy = 0,
                        CreateDate = DateTime.Now,
                        UpdateDate = DateTime.Now
                    });
                }
            }
            return flag;
        }

        /// <summary>
        /// 获取我的报名列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Commerce_Consult_Extend> GetUserJoinActivityPageList(int pageIndex, int pageSize, out long rowsCount, RB_Commerce_Consult_Extend dmodel)
        {
            return consultRepository.GetUserJoinActivityPageList(pageIndex, pageSize, out rowsCount, dmodel);
        }
    }
}