using System;
using System.Collections.Generic;
using System.Text;
using Mall.Model.Extend.User;
using Mall.Repository;
using System.Linq;
using Mall.Model.Entity.User;
using Mall.CacheManager.AppletWeChat;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Mall.Common.Plugin;
using NPOI.SS.Formula.Functions;
using Mall.Repository.User;
using Mall.Model.Extend.Statistics;
using Mall.Model.Query;
using VT.FW.DB;
using Mall.Model.Entity.Education;
using Mall.Repository.Education;

namespace Mall.Module.User
{
    /// <summary>
    /// 小程序处理类
    /// </summary>
    public class MiniProgramMsgModule
    {
        /// <summary>
        /// 商户仓储层对象
        /// </summary>
        private readonly RB_MiniProgramRepository programRepository = new RB_MiniProgramRepository();

        /// <summary>
        /// 会员订阅消息仓储层对象
        /// </summary>
        private readonly RB_Member_SubscriptionRepository subscriptionRepository = new Repository.User.RB_Member_SubscriptionRepository();

        /// <summary>
        /// 会员仓储层对象
        /// </summary>
        private readonly RB_Member_UserRepository userRepository = new Repository.User.RB_Member_UserRepository();

        /// <summary>
        ///  评论违规记录仓储
        /// </summary>
        private readonly RB_Education_ViolationLogRepository educationViolationLogRepository = new RB_Education_ViolationLogRepository();



        #region 发送小程序订阅信息




        /// <summary>
        /// 用户订阅消息
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetMemberSubscribe(RB_Member_Subscription_Extend demodel)
        {
            var gmodel = userRepository.GetEntity(demodel.UserId);
            if (gmodel == null)
            {
                return false;
            }

            var trans = subscriptionRepository.DbTransaction;
            try
            {
                foreach (var item in demodel.TempleteIdList)
                {
                    var list = subscriptionRepository.GetList(new RB_Member_Subscription_Extend() { OpenId = demodel.OpenId, Type = 1, TempleteId = item, MallBaseId = demodel.MallBaseId, TenantId = demodel.TenantId });
                    if (!list.Any())
                    {
                        subscriptionRepository.Insert(new RB_Member_Subscription()
                        {
                            UserId = demodel.UserId,
                            Id = 0,
                            OpenId = demodel.OpenId,
                            Status = 0,
                            TempleteId = item,
                            Type = 1,
                            Count = 1,
                            MallBaseId = gmodel.MallBaseId,
                            TenantId = gmodel.TenantId
                        }, trans);
                    }
                    else
                    {
                        // 增加订阅次数
                        var model = list.FirstOrDefault();
                        Dictionary<string, object> files = new Dictionary<string, object>() {
                            { nameof(RB_Member_Subscription.Count),model.Count++}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Member_Subscription.Id),
                                  FiledValue=model.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        subscriptionRepository.Update(files, wheres, trans);
                    }
                }
                subscriptionRepository.DBSession.Commit();
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetLXYGuestSubscribe");
                subscriptionRepository.DBSession.Rollback();
                return false;
            }
        }


        /// <summary>
        /// 获取订阅模板数量
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public List<RB_Member_Subscription_Extend> GetLXYSubscribeCountList(string openId, int MallBaseId, int TenantId)
        {
            return subscriptionRepository.GetList(new RB_Member_Subscription_Extend() { OpenId = openId, Type = 1, MallBaseId = MallBaseId, TenantId = TenantId });
        }

        /// <summary>
        /// 下单成功发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="OrderNo">订单编号</param>
        /// <param name="OrderCreate">下单时间</param>
        /// <param name="OrderPay">支付金额</param>
        /// <param name="GoodsName">商品</param>
        /// <returns></returns>
        public bool SendOrderSucceedMsg(int TenantId, int MallBaseId, string OpenId, string OrderNo, string OrderCreate, string OrderMoney, string GoodsName)
        {
            var appletWeChatModel = programRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();

            string token = WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            string wenXinResult = string.Empty;
            if (!string.IsNullOrWhiteSpace(token))
            {
                string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
                var postdata = new
                {
                    touser = OpenId,
                    template_id = appletWeChatModel.OrderSuccessTpl,
                    page = "pages/order/index/index",
                    data = new
                    {
                        character_string6 = new
                        {
                            value = OrderNo
                        },
                        date5 = new
                        {
                            value = OrderCreate
                        },
                        amount3 = new
                        {
                            value = "￥" + OrderMoney
                        },
                        thing1 = new
                        {
                            value = GoodsName
                        }
                    },
                    miniprogram_state = "developer"
                };

                wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");
                LogHelper.WriteInfo("下单成功发送订阅消息:" + wenXinResult);
                JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                int errcode = Convert.ToInt32(jo["errcode"].ToString());
                if (errcode == 0)
                {
                    //成功
                    return true;
                }
                else
                {
                    LogHelper.WriteInfo(string.Format("SendOrderSucceedMsg:wenXinResult:{0}", wenXinResult));
                }
            }
            return false;
        }


        /// <summary>
        /// 下单取消发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="OrderNo">订单编号</param>
        /// <param name="CancelReason">取消原因</param>
        /// <param name="OrderMoney">订单金额</param>
        /// <param name="GoodsName">商品</param>
        /// <returns></returns>
        public bool SendOrderCancelMsg(int TenantId, int MallBaseId, string OpenId, string OrderNo, string CancelReason, string OrderMoney, string GoodsName)
        {
            var appletWeChatModel = programRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();

            string token = WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            string wenXinResult = string.Empty;
            if (!string.IsNullOrWhiteSpace(token))
            {
                string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
                var postdata = new
                {
                    touser = OpenId,
                    template_id = appletWeChatModel.OrderCancelTpl,
                    page = "pages/order/index/index",
                    data = new
                    {
                        character_string1 = new
                        {
                            value = OrderNo
                        },
                        thing7 = new
                        {
                            value = CancelReason
                        },
                        amount4 = new
                        {
                            value = "￥" + OrderMoney
                        },
                        name8 = new
                        {
                            value = GoodsName
                        }
                    }
                };

                wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");
                LogHelper.WriteInfo("下单取消发送订阅消息:" + wenXinResult);
                JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                int errcode = Convert.ToInt32(jo["errcode"].ToString());
                if (errcode == 0)
                {
                    //成功
                    return true;
                }
                else
                {
                    LogHelper.Write(string.Format("SendOrderCancelMsg:wenXinResult:{0}", wenXinResult));
                }
            }
            return false;
        }

        /// <summary>
        /// 发货通知发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="Remark">备注</param>
        /// <param name="TrackingNumber">快递单号</param>
        /// <param name="Company">快递公司</param>
        /// <param name="GoodsName">商品名称</param>
        /// <returns></returns>
        public bool SendOrderDeliverMsg(int TenantId, int MallBaseId, string OpenId, string Remark, string TrackingNumber, string Company, string GoodsName)
        {
            var appletWeChatModel = programRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
            string token = WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            string wenXinResult = string.Empty;
            if (!string.IsNullOrWhiteSpace(token))
            {
                string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
                var postdata = new
                {
                    touser = OpenId,
                    template_id = appletWeChatModel.OrderDeliverGoodsTpl,
                    page = "pages/order/index/index",
                    data = new
                    {
                        thing8 = new
                        {
                            value = Remark
                        },
                        character_string4 = new
                        {
                            value = TrackingNumber
                        },
                        thing7 = new
                        {
                            value = Company
                        },
                        thing2 = new
                        {
                            value = GoodsName
                        }
                    }
                };

                wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");
                LogHelper.WriteInfo("发货通知发送订阅消息:" + wenXinResult);
                JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                int errcode = Convert.ToInt32(jo["errcode"].ToString());
                if (errcode == 0)
                {
                    //成功
                    return true;
                }
                else
                {
                    LogHelper.Write(string.Format("SendOrderDeliverMsg:wenXinResult:{0}", wenXinResult));
                }
            }
            return false;
        }


        /// <summary>
        /// 退款通知发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="Remark">退款原因</param>
        /// <param name="OrderNo">订单号</param>
        /// <param name="OrderMoney">退款金额</param>
        /// <param name="GoodsName">商品名称</param>
        /// <returns></returns>
        public bool SendOrderRefundMsg(int TenantId, int MallBaseId, string OpenId, string Remark, string OrderNo, string OrderMoney, string GoodsName)
        {
            var appletWeChatModel = programRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();

            string token = WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            string wenXinResult = string.Empty;
            if (!string.IsNullOrWhiteSpace(token))
            {
                string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
                var postdata = new
                {
                    touser = OpenId,
                    template_id = appletWeChatModel.RefundTpl,
                    page = "pages/order/index/index",
                    data = new
                    {
                        character_string4 = new
                        {
                            value = OrderNo
                        },
                        thing5 = new
                        {
                            value = GoodsName
                        },
                        amount2 = new
                        {
                            value = OrderMoney + "元"
                        },
                        thing1 = new
                        {
                            value = Remark
                        }
                    }
                };

                wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");
                LogHelper.WriteInfo("SendOrderRefundMsg 退款通知发送订阅消息:" + wenXinResult);
                JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                int errcode = Convert.ToInt32(jo["errcode"].ToString());
                if (errcode == 0)
                {
                    //成功
                    return true;
                }
                else
                {
                    LogHelper.Write(string.Format("SendOrderRefundMsg:wenXinResult:{0}", wenXinResult));
                }
            }
            return false;
        }


        /// <summary>
        /// 活动状态发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="ActivityName">活动名称</param>
        /// <param name="Progress">活动进度</param>
        /// <param name="Remark">温馨提示</param>
        /// <returns></returns>
        public bool SendActivityStateMsg(int TenantId, int MallBaseId, string OpenId, string ActivityName, string Progress, string Remark)
        {
            var appletWeChatModel = programRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();

            string token = WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            string wenXinResult = string.Empty;
            if (!string.IsNullOrWhiteSpace(token))
            {
                string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
                var postdata = new
                {
                    touser = OpenId,
                    template_id = appletWeChatModel.ActiveStateTpl,
                    page = Mall.Common.Config.FirstPage,
                    data = new
                    {
                        thing1 = new
                        {
                            value = ActivityName
                        },
                        thing2 = new
                        {
                            value = Progress
                        },
                        thing4 = new
                        {
                            value = Remark
                        }
                    }
                };

                wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");
                LogHelper.WriteInfo("活动状态发送订阅消息:" + wenXinResult);
                JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                int errcode = Convert.ToInt32(jo["errcode"].ToString());
                if (errcode == 0)
                {
                    //成功
                    return true;
                }
                else
                {
                    LogHelper.Write(string.Format("SendActivityStateMsg:wenXinResult:{0}", wenXinResult));
                }
            }
            return false;
        }

        /// <summary>
        /// 审核结果通知发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="Remark">审核说明</param>
        /// <param name="Result">审核结果</param>
        /// <param name="UserName">审核对象</param>
        /// <param name="CreateDate">审核时间</param>
        /// <returns></returns>
        public bool SendAuditResultMsg(int TenantId, int MallBaseId, string OpenId, string Remark, string Result, string UserName, string CreateDate)
        {
            var appletWeChatModel = programRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();

            string token = WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            string wenXinResult = string.Empty;
            if (!string.IsNullOrWhiteSpace(token))
            {
                string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
                var postdata = new
                {
                    touser = OpenId,
                    template_id = appletWeChatModel.AuditResultTpl,
                    page = Mall.Common.Config.FirstPage,
                    data = new
                    {
                        thing4 = new
                        {
                            value = Remark
                        },
                        phrase2 = new
                        {
                            value = Result
                        },
                        thing1 = new
                        {
                            value = UserName
                        },
                        time3 = new
                        {
                            value = CreateDate
                        }
                    }
                };
                wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");
                LogHelper.WriteInfo("审核结果通知发送订阅消息:" + wenXinResult);
                JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                int errcode = Convert.ToInt32(jo["errcode"].ToString());
                if (errcode == 0)
                {
                    //成功
                    return true;
                }
                else
                {
                    LogHelper.Write(string.Format("SendAuditResultMsg:wenXinResult:{0}", wenXinResult));
                }
            }
            return false;
        }


        /// <summary>
        /// 提现成功通知发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="Monry">提现金额</param>
        /// <param name="ServiceCharge">手续费</param>
        /// <param name="Type">打款方式</param>
        /// <param name="Remark">打款原因</param>
        /// <returns></returns>
        public bool SendWithdrawSucceedMsg(int TenantId, int MallBaseId, string OpenId, string Monry, string ServiceCharge, string Type, string Remark)
        {
            var appletWeChatModel = programRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();

            string token = WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            string wenXinResult = string.Empty;
            if (!string.IsNullOrWhiteSpace(token))
            {
                string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
                var postdata = new
                {
                    touser = OpenId,
                    template_id = appletWeChatModel.ReflectSuccessTpl,
                    page = Mall.Common.Config.FirstPage,
                    data = new
                    {
                        amount1 = new
                        {
                            value = "￥" + Monry
                        },
                        amount2 = new
                        {
                            value = "￥" + ServiceCharge
                        },
                        thing3 = new
                        {
                            value = Type
                        },
                        thing4 = new
                        {
                            value = Remark
                        }
                    }
                };
                wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");
                LogHelper.WriteInfo("提现成功通知发送订阅消息:" + wenXinResult);
                JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                int errcode = Convert.ToInt32(jo["errcode"].ToString());
                if (errcode == 0)
                {
                    //成功
                    return true;
                }
                else
                {
                    LogHelper.Write(string.Format("SendWithdrawSucceedMsg:wenXinResult:{0}", wenXinResult));
                }
            }
            return false;
        }


        /// <summary>
        /// 提现失败通知发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="Monry">提现金额</param>
        /// <param name="Remark">备注</param>
        /// <returns></returns>
        public bool SendWithdrawFailMsg(int TenantId, int MallBaseId, string OpenId, string Monry, string Remark)
        {
            var appletWeChatModel = programRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();

            string token = WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            string wenXinResult = string.Empty;
            if (!string.IsNullOrWhiteSpace(token))
            {
                string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
                var postdata = new
                {
                    touser = OpenId,
                    template_id = appletWeChatModel.ReflectFailTpl,
                    page = Mall.Common.Config.FirstPage,
                    data = new
                    {
                        amount1 = new
                        {
                            value = Monry
                        },
                        name2 = new
                        {
                            value = Remark
                        }
                    }
                };
                wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");
                LogHelper.WriteInfo("提现失败通知发送订阅消息:" + wenXinResult);
                JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                int errcode = Convert.ToInt32(jo["errcode"].ToString());
                if (errcode == 0)
                {
                    //成功
                    return true;
                }
                else
                {
                    LogHelper.Write(string.Format("SetLXYSubscribeSend:SendWithdrawFailMsg:{0}", wenXinResult));
                }
            }
            return false;
        }


        /// <summary>
        /// 会员等级通知发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="Remark">备注说明</param>
        /// <param name="CreateDate">变更时间</param>
        /// <returns></returns>
        public bool SendMemberLevelMsg(int TenantId, int MallBaseId, string OpenId, string Remark, string CreateDate)
        {
            var appletWeChatModel = programRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();

            string token = WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            string wenXinResult = string.Empty;
            if (!string.IsNullOrWhiteSpace(token))
            {
                string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
                var postdata = new
                {
                    touser = OpenId,
                    template_id = appletWeChatModel.MembersLevelChangeTpl,
                    page = Mall.Common.Config.FirstPage,
                    data = new
                    {
                        thing3 = new
                        {
                            value = Remark
                        },
                        date2 = new
                        {
                            value = CreateDate
                        }
                    }
                };
                wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");
                LogHelper.WriteInfo("会员等级通知发送订阅消息:" + wenXinResult);
                JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                int errcode = Convert.ToInt32(jo["errcode"].ToString());
                if (errcode == 0)
                {
                    //成功
                    return true;
                }
                else
                {
                    LogHelper.Write(string.Format("SendMemberLevelMsg:wenXinResult:{0}", wenXinResult));
                }
            }
            return false;
        }



        /// <summary>
        /// 检查是否返回图片路径
        /// </summary>
        /// <param name="picStr"></param>
        /// <param name="TCID"></param>
        /// <param name="ConfigId"></param>
        /// <returns></returns>
        public string CheckWeiXinShareImg(string picStr, RB_MiniProgram_Extend model, string jumpUrl)
        {
            if (string.IsNullOrWhiteSpace(picStr))
            {

                string token = WeiXinReidsCache.Get(model.MiniAppId);
                if (string.IsNullOrEmpty(token))
                {
                    token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, model.MiniAppId, model.MiniAppSecret);
                    System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(model.MiniAppId, token));
                }
                if (string.IsNullOrEmpty(token))
                {
                    return "";
                }
                picStr = GetWeiXinShare(model, jumpUrl);
            }
            return picStr;
        }

        /// <summary>
        /// 获取微信小程序分享
        /// </summary>
        /// <returns></returns>
        public string GetWeiXinShare(RB_MiniProgram_Extend model, string jumpUrl)
        {
            string access_TokenStr = WeiXinReidsCache.Get(model.MiniAppId);
            if (string.IsNullOrEmpty(access_TokenStr))
            {
                access_TokenStr = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(access_TokenStr, model.MiniAppId, model.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(model.MiniAppId, access_TokenStr));
            }
            string picStr = string.Empty;
            if (!string.IsNullOrWhiteSpace(access_TokenStr))
            {
                string GetImageUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_TokenStr;
                var postData = new
                {
                    scene = "",
                    page = jumpUrl,
                    width = "100",
                    is_hyaline = true
                };
                picStr = HttpHelper.HttpPost(GetImageUrl, JsonHelper.Serialize(postData));
                //if (string.IsNullOrWhiteSpace(picStr))
                //{

                //    picStr = CheckWeiXinShareImg(picStr, model, jumpUrl);

                //}
            }
            return picStr;
        }





        /// <summary>
        /// 老师发布动态发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="Remark">退款原因</param>
        /// <param name="OrderNo">订单号</param>
        /// <param name="OrderMoney">退款金额</param>
        /// <param name="GoodsName">商品名称</param>
        /// <returns></returns>
        public bool SendEducationDynamicMsg(int TenantId, int MallBaseId, List<string> OpenIds, string Title, string UserName, string CreateTime)
        {
            var appletWeChatModel = programRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();

            string token = WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            string wenXinResult = string.Empty;
            int successCount = 0;
            if (!string.IsNullOrWhiteSpace(token))
            {
                try
                {
                    foreach (var item in OpenIds)
                    {
                        if (!string.IsNullOrWhiteSpace(item))
                        {
                            string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
                            var postdata = new
                            {
                                touser = item,
                                template_id = appletWeChatModel.EducationDynamicTpl,
                                page = "pages/order/index/index",
                                data = new
                                {
                                    thing1 = new
                                    {
                                        value = Title
                                    },
                                    thing2 = new
                                    {
                                        value = UserName
                                    },
                                    time3 = new
                                    {
                                        value = CreateTime
                                    }
                                }
                            };

                            wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");
                            LogHelper.WriteInfo("老师发布动态发送订阅消息:" + wenXinResult);
                            JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                            int errcode = Convert.ToInt32(jo["errcode"].ToString());
                            if (errcode == 0)
                            {
                                successCount += 1;
                            }
                            else
                            {
                                LogHelper.Write(string.Format("SendEducationDynamicMsg:wenXinResult:{0}", wenXinResult));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Common.Plugin.LogHelper.Write(ex, "SendEducationDynamicMsg");
                    LogHelper.Write(string.Format("SendEducationDynamicMsg:wenXinResult:{0}", wenXinResult));
                }
                if (successCount == OpenIds.Count())
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            return false;
        }






        /// <summary>
        /// 老师发布动态发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="Remark">退款原因</param>
        /// <param name="OrderNo">订单号</param>
        /// <param name="OrderMoney">退款金额</param>
        /// <param name="GoodsName">商品名称</param>
        /// <returns></returns>
        public bool SendCourseOrderTplMsg(int TenantId, int MallBaseId, List<string> OpenIds, string Title, string UserName, string CreateTime)
        {
            var appletWeChatModel = programRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();

            string token = WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            string wenXinResult = string.Empty;
            int successCount = 0;
            if (!string.IsNullOrWhiteSpace(token))
            {
                try
                {
                    foreach (var item in OpenIds)
                    {
                        if (!string.IsNullOrWhiteSpace(item))
                        {
                            string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
                            var postdata = new
                            {
                                touser = item,
                                template_id = appletWeChatModel.CourseOrderTpl,
                                page = "pages/appointment/personal/studentAppointmentList",
                                data = new
                                {
                                    thing1 = new
                                    {
                                        value = Title.Length > 20 ? Title.Substring(0, 15) : Title
                                    },
                                    thing2 = new
                                    {
                                        value = UserName.Length > 20 ? UserName.Substring(0, 18) : UserName
                                    },
                                    time4 = new
                                    {
                                        value = CreateTime
                                    }
                                }
                            };

                            wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");
                            LogHelper.WriteInfo("老师确认房间信息发送推送消息:" + wenXinResult);
                            JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                            int errcode = Convert.ToInt32(jo["errcode"].ToString());
                            if (errcode == 0)
                            {
                                successCount += 1;
                            }
                            else
                            {
                                LogHelper.Write(string.Format("SendCourseOrderTplMsg:wenXinResult:{0}", wenXinResult));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "SendCourseOrderTplMsg");
                    LogHelper.Write(string.Format("SendCourseOrderTplMsg:wenXinResult:{0}", wenXinResult));
                }
                if (successCount == OpenIds.Count())
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            return false;
        }




        /// <summary>
        /// 审核首店/公司发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="Remark">退款原因</param>
        /// <param name="OrderNo">订单号</param>
        /// <param name="OrderMoney">退款金额</param>
        /// <param name="GoodsName">商品名称</param>
        /// <returns></returns>
        public bool SendHatchExamineMsg(int TenantId, int MallBaseId, List<string> OpenIds, string result, string typeName, string CreateTime)
        {
            var appletWeChatModel = programRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();

            string token = WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            string wenXinResult = string.Empty;
            int successCount = 0;
            if (!string.IsNullOrWhiteSpace(token))
            {
                try
                {
                    foreach (var item in OpenIds)
                    {
                        if (!string.IsNullOrWhiteSpace(item))
                        {
                            string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
                            var postdata = new
                            {
                                touser = item,
                                template_id = appletWeChatModel.HatchExamineTpl,
                                page = "pages/user-center/user-center",
                                data = new
                                {
                                    phrase1 = new
                                    {
                                        value = result
                                    },
                                    date7 = new
                                    {
                                        value = CreateTime
                                    },
                                    name8 = new
                                    {
                                        value = typeName
                                    }
                                }
                            };

                            wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");
                            LogHelper.WriteInfo("首店审核/公司审核发送通知消息:" + wenXinResult);
                            JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                            int errcode = Convert.ToInt32(jo["errcode"].ToString());
                            if (errcode == 0)
                            {
                                successCount += 1;
                            }
                            else
                            {
                                LogHelper.Write(string.Format("SendHatchExamineMsg:wenXinResult:{0}", wenXinResult));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Common.Plugin.LogHelper.Write(ex, "SendHatchExamineMsg");
                    LogHelper.Write(string.Format("SendHatchExamineMsg:wenXinResult:{0}", wenXinResult));
                }
                if (successCount == OpenIds.Count())
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            return false;
        }

        #endregion

        #region  评论违规检测 
        /// <summary>
        /// 违规文字检测
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <returns></returns>
        public int CheckViolation(RB_MiniProgram_Extend model, string content)
        {
            var appletWeChatModel = programRepository.GetListRepository(model).FirstOrDefault();

            string token = WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return 0;
            }
            string wenXinResult = string.Empty;
            if (!string.IsNullOrWhiteSpace(token))
            {
                string Url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + token;
                var postdata = new
                {
                    content
                };
                wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");
                LogHelper.WriteInfo("下单成功发送订阅消息:" + wenXinResult);
                JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                int errcode = Convert.ToInt32(jo["errcode"].ToString());
                if (errcode == 0)
                {
                    //成功
                    return 2;
                }
                else
                {
                    LogHelper.WriteInfo(string.Format("CheckViolation:wenXinResult:{0}", wenXinResult));
                    return 1;
                }
            }
            return 0;
        }

        #region 评论违规记录
        /// <summary>
        /// 获取用户的违规记录
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Education_ViolationLog> GetViolationLogList(RB_Education_ViolationLog query)
        {
            return educationViolationLogRepository.GetListRepository(query);
        }

        /// <summary>
        /// 新增用户的违规记录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetEducationViolationLog(RB_Education_ViolationLog model)
        {
            return educationViolationLogRepository.Insert(model) > 0;
        }

        /// <summary>
        /// 将用户加入黑名单
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public bool UpdateUserBlacklist(int TenantId, int MallBaseId, int UserId)
        {
            Dictionary<string, object> cols = new Dictionary<string, object>()
            {
                { nameof(RB_Member_User.Blacklist),1}
            };
            List<WhereHelper> wheres = new List<WhereHelper>()
            {
                  new WhereHelper(){
                      FiledName=nameof(RB_Member_User.Id),
                     FiledValue=UserId,
                     OperatorEnum=OperatorEnum.Equal
                  },
                    new WhereHelper(){
                                            FiledName=nameof(RB_Member_User.TenantId),
                                            FiledValue=TenantId,
                                            OperatorEnum=OperatorEnum.Equal
                                    },
                                    new WhereHelper(){
                                            FiledName=nameof(RB_Member_User.MallBaseId),
                                            FiledValue=MallBaseId,
                                            OperatorEnum=OperatorEnum.Equal
                                    }
            };
            return userRepository.Update(cols, wheres);
        }
        #endregion

        #endregion


    }
}
