///// <summary>
        ///// 取得口令回复一览
        ///// </summary>
        ///// <param name="autoReplyView"></param>
        ///// <returns></returns>
        //private List<AutoReplyContentView> GetAutoReplyList(AutoReplyView autoReplyView)
        //{
        //    // THIS IS NOT A GOOD WAY, SHOULD TRANSFER TO JSON OBJECT IN FRONT END
        //    var list = new List<AutoReplyContentView>();
        //    var replyTypes = Request.Form.GetValues("replyType");
        //    var textReply = Request.Form.Get("saytext");
        //    var newsTitle = Request.Form.Get("msgPictitle");
        //    var newsComment = Request.Form.Get("msgtips");
        //    var newsBody = Request.Form.Get("msgbody");
        //    //var isTextEncrypts = Request.Form.GetValues("isTextEncryptReplace");
        //    var replyNewsTypes = Request.Form.GetValues("replyNewsType");
        //    var replyNewsLatestCounts = Request.Form.GetValues("replyNewsLatestCount");
        //    var replyNewsLists = Request.Form.GetValues("replyNewsList");
        //    var textReplyFiles = Request.Form.GetValues("textReplyFiles");

        //    //if (replyTypes != null)
        //    //{
        //    //    var count = replyTypes.Length;
        //    //    for (int i = 0; i < count; i++)
        //    //    {
        //            var content = new AutoReplyContentView();
        //            content.AutoReplyId = autoReplyView.Id;
        //            content.PrimaryType = 2;//int.Parse(replyTypes[i]);
        //            NewsInfoView view = new NewsInfoView();
        //            switch (content.PrimaryType)
        //            {
        //                #region text
        //                case (int)AutoReplyContentEnum.TEXT:
        //                case (int)AutoReplyContentEnum.LINK:
        //                    {
        //                        content.Content = textReply;
        //                        //if (isTextEncrypts != null)
        //                        //{
        //                        //    content.IsEncrypt = isTextEncrypts[i] == "1";
        //                        //}
        //                        break;
        //                    }
        //                #endregion

        //                #region news
        //                case (int)AutoReplyContentEnum.PHOTO_TEXT:
        //                    {
        //                        view.NewsTitle = newsTitle;
        //                        view.NewsComment = newsComment;
        //                        view.NewsContent = newsBody;
        //                        //    //ImageContent = news
        //                        content.NewsID = Guid.NewGuid().ToString();
        //                        var configs = Infrastructure.Web.Domain.Service.CommonService.lstSysConfig;
        //                        var config = configs.Where(a => a.ConfigName.Equals("Content Server", StringComparison.CurrentCultureIgnoreCase)).First();
        //                        string host = config.ConfigValue;
        //                        if (host.EndsWith("/"))
        //                        {
        //                            host = host.Substring(0, host.Length - 1);
        //                        }
        //                        //var picUrl = host + item.ImageContent;
        //                        var url = host + "WechatMain/AutoReply/GetNews?id=" + content.NewsID;
        //                        content.Content = JsonConvert.SerializeObject(view);
        //                        //if (replyNewsTypes != null)
        //                        //{
        //                        //    content.SecondaryType = int.Parse(replyNewsTypes[i]);
        //                        //    if (content.SecondaryType == (int)AutoReplyNewsEnum.LATEST)
        //                        //    {
        //                        //        if (replyNewsLatestCounts != null) content.Content = replyNewsLatestCounts[i];
        //                        //    }
        //                        //    else if (content.SecondaryType == (int)AutoReplyNewsEnum.MANUAL)
        //                        //    {
        //                        //        if (replyNewsLists != null) content.NewsID = replyNewsLists[i];
        //                        //    }
        //                        //}

        //                        break;
        //                    }
        //                #endregion

        //                case (int)AutoReplyContentEnum.VIDEO:
        //                    view.NewsTitle = newsTitle;
        //                    break;
        //                case (int)AutoReplyContentEnum.FILE:
        //                    view.NewsTitle = newsTitle;
        //                    break;
        //                case (int)AutoReplyContentEnum.IMAGE:
        //                    view.NewsTitle = newsTitle;
        //                    break;
        //                case (int)AutoReplyContentEnum.AUDIO:
        //                    view.NewsTitle = newsTitle;
        //                    break;
        //                default:
        //                    {
        //                        //if (textReplyFiles != null) content.FileID = int.Parse(textReplyFiles[i]);
        //                        break;
        //                    }
        //            }

        //            list.Add(content);
        //    //    }

        //    //}

        //    return list;
        //}
        #endregion

        private List <AutoReplyContentView> GetAutoReplyList(AutoReplyNewView model)
        {
            var list    = new List <AutoReplyContentView>();
            var content = new AutoReplyContentView();

            content.AutoReplyId = model.Main.Id;
            var news = model.Send[0]; //保存多条内容。只有新闻存在多条情况

            content.IsEncrypt = news.isSecurityPost;
            var cate = (AutoReplyContentEnum)Enum.Parse(typeof(AutoReplyContentEnum), news.NewsCate, true);

            //选择资源文件
            if (news.materialId.HasValue && news.materialId.Value > 0)
            {
                var config = WeChatCommonService.GetWeChatConfigByID(model.Main.AppId);
                content.FileID       = news.materialId;
                content.IsNewContent = false;
                //更新MediaID
                //out 之后news.isSecurityPost 被清空
                Innocellence.WeChatMain.Common.WechatCommon.GetMediaIDByFileID(news.materialId, _attachmentsItemService, config.WeixinCorpId, out news);

                content.Content = JsonConvert.SerializeObject(new List <NewsInfoView> {
                    news
                });
            }
            else if (cate == AutoReplyContentEnum.NEWS)
            {                                          //图文消息特殊处理
                if (string.IsNullOrEmpty(news.NewsID)) //如果不是选择的素材
                {
                    var listArticle = GetArticleList(model.Send);

                    content.NewsID = string.Join(",", listArticle.Select(a => a.Id).ToArray());
                }
                else
                {
                    content.NewsID = news.NewsID;
                }
                content.IsNewContent = false;
                //content.SecondaryType = model.Main.Contents[0].SecondaryType;
                content.SecondaryType = (int)AutoReplyNewsEnum.MANUAL; //此处缺少功能,临时写死。画面应该增加返回最近的几条新闻
            }
            else
            {
                if (cate != AutoReplyContentEnum.TEXT && cate != AutoReplyContentEnum.LINK) //上传文件处理
                {
                    var mediaId = WechatCommon.GetMediaInfo(cate, news, model.Main.AppId);
                    content.MediaId = mediaId;
                }


                content.IsNewContent = true;
                //content.Content = JsonConvert.SerializeObject(model.Send);  //这个地方不应该存数组,todo
                content.Content = JsonConvert.SerializeObject(new List <NewsInfoView> {
                    news
                });
            }
            content.PrimaryType = (int)cate;
            list.Add(content);
            return(list);
        }
        public ActionResult GetNews(int id, int?subId)
        {
            var view = new AutoReplyNewView();

            view.Main = _autoReplyService.GetDetail(id);
            var news = JsonConvert.DeserializeObject <List <NewsInfoView> >(view.Main.Contents[0].Content)[0];

            return(View(news));
        }
        public JsonResult GetContent(int id)
        {
            var view = new AutoReplyNewView();

            view.Main = _autoReplyService.GetDetail(id);
            if (view.Main.Contents[0].IsNewContent.Value)
            {
                view.Send = JsonConvert.DeserializeObject <List <NewsInfoView> >(view.Main.Contents[0].Content);
            }
            else
            {
                if (view.Main.Contents[0].PrimaryType == (int)AutoReplyContentEnum.TEXT)
                {
                    view.Send = new List <NewsInfoView>()
                    {
                        new NewsInfoView()
                        {
                            NewsCate = "text", NewsContent = view.Main.Contents[0].Content, isSecurityPost = view.Main.Contents[0].IsEncrypt
                        }
                    };
                }
                else if ((view.Main.Contents[0].PrimaryType == (int)AutoReplyContentEnum.VIDEO ||
                          view.Main.Contents[0].PrimaryType == (int)AutoReplyContentEnum.VOICE ||
                          view.Main.Contents[0].PrimaryType == (int)AutoReplyContentEnum.IMAGE ||
                          view.Main.Contents[0].PrimaryType == (int)AutoReplyContentEnum.FILE) && view.Main.Contents[0].FileID.HasValue)
                {
                    var fileInfo = _fileManageService.GetById <AttachmentsItemView>(view.Main.Contents[0].FileID.Value);

                    view.Send = new List <NewsInfoView>()
                    {
                        new NewsInfoView()
                        {
                            NewsCate     = Enum.Parse(typeof(AutoReplyContentEnum), view.Main.Contents[0].PrimaryType.ToString()).ToString().ToLower(), NewsContent = "",
                            AppId        = view.Main.AppId, NewsTitle = fileInfo.AttachmentTitle, ImageContent = "/" + fileInfo.ThumbUrl, VideoContent = "/" + fileInfo.AttachmentUrl, FileSrc = "/" + fileInfo.AttachmentUrl,
                            SoundSrc     = "/" + fileInfo.AttachmentUrl, MediaId = fileInfo.MediaId, NewsComment = fileInfo.Description, isSecurityPost = view.Main.Contents[0].IsEncrypt,
                            RealFileName = fileInfo.AttachmentTitle
                        }
                    };
                }
                else if (view.Main.Contents[0].PrimaryType == (int)AutoReplyContentEnum.NEWS && !string.IsNullOrEmpty(view.Main.Contents[0].NewsID))
                {
                    var    ListArticle = _articleInfoService.GetListByNewsIDs(view.Main.Contents[0].NewsID);
                    string strCate     = Enum.Parse(typeof(AutoReplyContentEnum), view.Main.Contents[0].PrimaryType.ToString()).ToString().ToLower();
                    ListArticle.ForEach(a => { a.NewsCate = strCate; a.isSecurityPost = view.Main.Contents[0].IsEncrypt; a.NewsID = view.Main.Contents[0].NewsID; });
                    view.Send = ListArticle;
                }
            }
            view.GetExtraContent(view.Main.Contents);
            return(Json(view, JsonRequestBehavior.AllowGet));
        }
        public ActionResult GetNews(int id, int?subId, int type, bool?isPreview)
        {
            if (string.IsNullOrEmpty(ViewBag.WeChatUserID))
            {
                return(Redirect("/notauthed.html"));
            }
            NewsTypeEnum typeEnum = (NewsTypeEnum)type;

            switch (typeEnum)
            {
            case NewsTypeEnum.Message:
                if (isPreview.HasValue && isPreview.Value)
                {
                    var model = _previewMessageLogService.Repository.Entities.Where(a => a.Id == id && a.ContentType == (int)WechatMessageLogType.news).FirstOrDefault();
                    if (model != null)
                    {
                        var list = JsonConvert.DeserializeObject <List <NewsInfoView> >(model.Content);
                        ViewBag.Content     = list.Where(a => a.Id == subId).First();
                        ViewBag.CreatedTime = model.CreatedTime.ToString("yyyy-MM-dd");
                    }
                }
                else
                {
                    var model = _messageLogService.Repository.Entities.Where(a => a.Id == id && a.ContentType == (int)WechatMessageLogType.news).FirstOrDefault();
                    if (model != null)
                    {
                        var list = JsonConvert.DeserializeObject <List <NewsInfoView> >(model.Content);
                        ViewBag.Content     = list.Where(a => a.Id == subId).First();
                        ViewBag.CreatedTime = model.CreatedTime.ToString("yyyy-MM-dd");
                    }
                }
                break;

            case NewsTypeEnum.AutoReply:
                var view = new AutoReplyNewView();
                view.Main = _autoReplyService.GetDetail(id);
                var news = JsonConvert.DeserializeObject <List <NewsInfoView> >(view.Main.Contents[0].Content)[0];
                ViewBag.Content     = news;
                ViewBag.CreatedTime = view.Main.CreatedDate.Value.ToString("yyyy-MM-dd");
                break;

            default:
                break;
            }
            return(View());
        }
        public JsonResult EditPost(AutoReplyNewView model)
        {
            var wechatConfig = WeChatCommonService.GetWeChatConfigByID(model.Main.AppId);

            if (string.IsNullOrWhiteSpace(model.Main.Description))
            {
                model.Main.Description = string.Empty;
            }

            // 口令类型
            model.Main.Keywords = GetAutoReplySubTypes(model);

            // 口令回复
            model.Main.Contents = GetAutoReplyList(model);

            //if (!wechatConfig.IsCorp.Value)
            //{
            model.SetExtraContent(model.Main.Contents);
            //}

            // 输入校验
            //if (!BeforeAddOrUpdate(model) || !ModelState.IsValid)
            //{
            //    return Json(GetErrorJson(), JsonRequestBehavior.AllowGet);
            //}

            // add
            if (model.Main.Id == 0)
            {
                _autoReplyService.Add(model.Main);
            }
            // Edit
            else
            {
                _autoReplyService.Update(model.Main);
            }

            //return RedirectToAction("Index", new RouteValueDictionary { {"appId", appId} });
            return(Json(doJson(null), JsonRequestBehavior.AllowGet));
        }
        /// <summary>
        /// 取得口令子类型数据
        /// </summary>
        /// <param name="autoReplyView"></param>
        /// <returns></returns>
        private List <AutoReplyKeywordView> GetAutoReplySubTypes(AutoReplyNewView model)
        {
            var list = new List <AutoReplyKeywordView>();

            switch (model.Main.KeywordType)
            {
            // 文本类型
            case (int)AutoReplyKeywordEnum.TEXT:
            {
                var matchTypes = model.Main.MatchType;
                var keywords   = model.Main.TextKeyword;
                if (matchTypes != null && keywords != null)
                {
                    var keywordCount = keywords.Count;
                    for (int i = 0; i < matchTypes.Count; i++)
                    {
                        if (keywordCount > i)
                        {
                            var keywordObj = new AutoReplyKeywordView
                            {
                                AutoReplyId   = model.Main.Id,
                                SecondaryType = matchTypes[i],
                                Keyword       = keywords[i]
                            };

                            list.Add(keywordObj);
                        }
                    }
                }
                break;
            }

            // 菜单类型
            case (int)AutoReplyKeywordEnum.MENU:
            {
                var keywordObj = new AutoReplyKeywordView();
                keywordObj.AutoReplyId   = model.Main.Id;
                keywordObj.SecondaryType = model.Main.MatchType[0];
                // 普通类型时,有菜单key
                if (keywordObj.SecondaryType == (int)AutoReplyMenuEnum.NORMAL)
                {
                    keywordObj.Keyword = model.Main.TextKeyword[0];
                }
                list.Add(keywordObj);

                break;
            }

            //case (int)AutoReplyKeywordEnum.SubscribeEvent:
            case (int)AutoReplyMPKeywordEnum.SCAN:
            case (int)AutoReplyMPKeywordEnum.SubscribeWithScan:
            {
                var keywordObj = new AutoReplyKeywordView();
                keywordObj.AutoReplyId = model.Main.Id;
                keywordObj.Keyword     = model.Main.TextKeyword[0];
                list.Add(keywordObj);
                break;
            }
            }

            return(list);
        }
        //public List<FileManageView> GetFileListPrivate(Expression<Func<FileManage, bool>> predicate, PageCondition ConPage)
        //{
        //    //predicate = predicate.AndAlso(x => x.CreatedUserID.Equals(User.Identity.Name));

        //    ConPage.SortConditions.Add(new SortCondition("CreatedDate", System.ComponentModel.ListSortDirection.Descending));

        //    var q = _fileManageService.GetList<FileManageView>(predicate, ConPage);

        //    return q.ToList();
        //}

        //BackEnd校验
        private bool BeforeAddOrUpdate(AutoReplyNewView modal)
        {
            var validate = true;
            var errMsg   = new StringBuilder();
            var objModal = modal.Main;

            if (string.IsNullOrEmpty(objModal.Name) || objModal.Name.Length > 20)
            {
                validate = false;
                errMsg.Append(T("请输入20字符以内的口令名称.<br/>"));
            }

            if (objModal.KeywordType == 0)
            {
                validate = false;
                errMsg.Append(T("请输入口令类型.<br/>"));
            }

            // 口令校验
            if (objModal.KeywordType == (int)AutoReplyKeywordEnum.TEXT ||
                objModal.KeywordType == (int)AutoReplyKeywordEnum.MENU)
            {
                if (objModal.Keywords == null || objModal.Keywords.Count == 0)
                {
                    validate = false;
                    errMsg.Append(T("请输入口令内容.<br/>"));
                }
                else
                {
                    if (objModal.KeywordType == (int)AutoReplyKeywordEnum.TEXT)
                    {
                        foreach (var keyword in objModal.Keywords)
                        {
                            if (String.IsNullOrEmpty(keyword.Keyword) || keyword.Keyword.Length > 20)
                            {
                                validate = false;
                                errMsg.Append(T("请输入20字符以内的口令.<br/>"));
                            }
                        }
                    }
                    else if (objModal.KeywordType == (int)AutoReplyKeywordEnum.MENU &&
                             objModal.Keywords[0].SecondaryType == (int)AutoReplyMenuEnum.NORMAL)
                    {
                        validate = false;
                        errMsg.Append(T("请输入20字符以内的菜单Key.<br/>"));
                    }
                }
            }

            // 口令回复内容校验
            if (objModal.Contents == null || objModal.Contents.Count == 0)
            {
                validate = false;
                errMsg.Append(T("请输入口令回复内容.<br/>"));
            }
            else
            {
                foreach (var content in objModal.Contents)
                {
                    switch (content.PrimaryType)
                    {
                    case (int)AutoReplyContentEnum.TEXT:
                    case (int)AutoReplyContentEnum.LINK:
                    {
                        if (String.IsNullOrEmpty(content.Content))
                        {
                            validate = false;
                            errMsg.Append(T("请输入口令回复内容.<br/>"));
                        }
                        break;
                    }

                    case (int)AutoReplyContentEnum.NEWS:
                    {
                        // 如果是选择最近几条新闻
                        if (content.SecondaryType == (int)AutoReplyNewsEnum.LATEST)
                        {
                            if (String.IsNullOrEmpty(content.Content))
                            {
                                validate = false;
                                errMsg.Append(T("请输入最新图文消息条数.<br/>"));
                            }
                        }
                        else if (content.SecondaryType == (int)AutoReplyNewsEnum.MANUAL)
                        {
                            if (String.IsNullOrEmpty(content.NewsID))
                            {
                                validate = false;
                                errMsg.Append(T("请选择图文消息"));
                            }
                        }
                        break;
                    }

                    default:
                    {
                        if (content.FileID == null || content.FileID == 0)
                        {
                            validate = false;
                            errMsg.Append(T("请选择文件"));
                        }
                        break;
                    }
                    }
                }
            }

            if (!validate)
            {
                ModelState.AddModelError("Invalid Input", errMsg.ToString());
            }

            return(validate);
        }