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;

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>
        /// <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);
        }
    }
}
