using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using Edu.Cache.WeChat;
using Edu.Common;
using Edu.Common.API;
using Edu.Common.Enum.WeChat;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.Entity.EduTask;
using Edu.Model.Public;
using Edu.Model.ViewModel.WeChat;
using Edu.Repository.EduTask;
using Edu.Repository.WeChat;
using Edu.ThirdCore.GZHWeChat;
using Edu.ThirdCore.QYWinXin;
using Edu.ThirdCore.QYWinXin.Model;
using Newtonsoft.Json.Linq;
using Senparc.Weixin.MP.AdvancedAPIs.GroupMessage;
using VT.FW.DB;

namespace Edu.Module.QYWeChat
{
    /// <summary>
    /// 投稿管理处理类
    /// </summary>
    public class QYContributeModule
    {
        /// <summary>
        /// 投稿配置
        /// </summary>
        private readonly RB_Contribute_ConfigRepository contribute_ConfigRepository = new RB_Contribute_ConfigRepository();
        /// <summary>
        /// 投稿信息
        /// </summary>
        private readonly RB_Contribute_InfoRepository contribute_InfoRepository = new RB_Contribute_InfoRepository();
        /// <summary>
        /// 投稿发布记录
        /// </summary>
        private readonly RB_Contribute_PublishLogRepository contribute_PublishLogRepository = new RB_Contribute_PublishLogRepository();
        /// <summary>
        /// 素材分组
        /// </summary>
        private readonly RB_Contribute_MediumGroupRepository contribute_MediumGroupRepository = new RB_Contribute_MediumGroupRepository();
        /// <summary>
        /// 素材
        /// </summary>
        private readonly RB_Contribute_MediumRepository contribute_MediumRepository = new RB_Contribute_MediumRepository();
        /// <summary>
        /// 小程序信息
        /// </summary>
        private readonly RB_Contribute_AppletRepository contribute_AppletRepository = new RB_Contribute_AppletRepository();
        /// <summary>
        /// 投稿日志
        /// </summary>
        private readonly RB_Contribute_InfoLogRepository contribute_InfoLogRepository = new RB_Contribute_InfoLogRepository();

        /// <summary>
        /// 教务单据
        /// </summary>
        private readonly RB_Education_ReceiptRepository education_ReceiptRepository = new RB_Education_ReceiptRepository();


        #region 投稿配置

        /// <summary>
        /// 获取配置
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public RB_Contribute_Config_ViewModel GetContributeConfigInfo(int groupId, int type)
        {
            var model = contribute_ConfigRepository.GetList(new RB_Contribute_Config_ViewModel() { Group_Id = groupId, Type = (ContributeConfigTypeEnum)type }).FirstOrDefault();
            return model;
        }

        /// <summary>
        /// 新增修改配置
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string SetContributeConfigInfo(RB_Contribute_Config_ViewModel model)
        {
            bool flag = false;
            if (model.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Contribute_Config_ViewModel.Name), model.Name},
                    { nameof(RB_Contribute_Config_ViewModel.AppId), model.AppId},
                    { nameof(RB_Contribute_Config_ViewModel.AppSecret), model.AppSecret},
                    { nameof(RB_Contribute_Config_ViewModel.Enable), model.Enable},
                    { nameof(RB_Contribute_Config_ViewModel.UpdateBy), model.UpdateBy},
                    { nameof(RB_Contribute_Config_ViewModel.UpdateTime), model.UpdateTime},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName = nameof(RB_Contribute_Config_ViewModel.Id),
                          FiledValue = model.Id,
                           OperatorEnum = OperatorEnum.Equal
                    }
                };
                flag = contribute_ConfigRepository.Update(keyValues, wheres);
            }
            else {
                #region 验证平台
                var oldList = contribute_ConfigRepository.GetList(new RB_Contribute_Config_ViewModel() { Group_Id = model.Group_Id, Type = model.Type });
                if (oldList.Any()) {
                    return "该平台已存在配置，无法新增";
                }
                #endregion
                flag = contribute_ConfigRepository.Insert(model) > 0;
            }
            return flag ? "" : "出错了，请联系管理员";
        }

        #endregion

        #region 素材管理

        /// <summary>
        /// 获取素材分组分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Contribute_MediumGroup_ViewModel> GetContributeMediumGroupPageList(int pageIndex, int pageSize, out long count, RB_Contribute_MediumGroup_ViewModel demodel)
        {
            return contribute_MediumGroupRepository.GetPageList(pageIndex, pageSize, out count, demodel);
        }

        /// <summary>
        /// 获取素材分组列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Contribute_MediumGroup_ViewModel> GetContributeMediumGroupList(RB_Contribute_MediumGroup_ViewModel demodel)
        {
            return contribute_MediumGroupRepository.GetList(demodel);
        }

        /// <summary>
        /// 新增修改分组
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetContributeMediumGroup(RB_Contribute_MediumGroup_ViewModel demodel)
        {
            bool flag;
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Contribute_MediumGroup_ViewModel.Name),demodel.Name},
                    { nameof(RB_Contribute_MediumGroup_ViewModel.Sort),demodel.Sort},
                    { nameof(RB_Contribute_MediumGroup_ViewModel.UpdateBy),demodel.UpdateBy},
                    { nameof(RB_Contribute_MediumGroup_ViewModel.UpdateTime),demodel.UpdateTime},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Contribute_MediumGroup_ViewModel.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                flag = contribute_MediumGroupRepository.Update(keyValues, wheres);
            }
            else
            {
                flag = contribute_MediumGroupRepository.Insert(demodel) > 0;
            }
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 删除分组
        /// </summary>
        /// <param name="mediumId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string DelContributeMediumGroup(int mediumId, UserInfo userInfo)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Contribute_MediumGroup_ViewModel.Status),1},
                { nameof(RB_Contribute_MediumGroup_ViewModel.UpdateBy),userInfo.Id},
                { nameof(RB_Contribute_MediumGroup_ViewModel.UpdateTime),DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Contribute_MediumGroup_ViewModel.Id),
                        FiledValue=mediumId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            var flag = contribute_MediumGroupRepository.Update(keyValues, wheres);
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 获取素材分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Contribute_Medium_ViewModel> GetContributeMediumPageList(int pageIndex, int pageSize, out long count, RB_Contribute_Medium_ViewModel demodel)
        {
            var list = contribute_MediumRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any()) {
                var groupIds = string.Join(",", list.Select(x => x.MediaGroupId).Distinct());
                var glist = contribute_MediumGroupRepository.GetList(new RB_Contribute_MediumGroup_ViewModel() { Group_Id = demodel.Group_Id, MediumGroupIds = groupIds });
                foreach (var item in list) {
                    item.MediaGroupName = glist.Where(x => x.Id == item.MediaGroupId).FirstOrDefault()?.Name ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 新增修改素材
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetContributeMediumInfo(RB_Contribute_Medium_ViewModel demodel)
        {
            if (demodel.Id > 0)
            {
                var oldModel = contribute_MediumRepository.GetEntity(demodel.Id);
                if (oldModel == null || oldModel.Status == 1) { return "该素材已不存在"; }
                if (oldModel.Type != demodel.Type) { return "素材类型有误"; }
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Contribute_Medium_ViewModel.UpdateBy), demodel.UpdateBy},
                    { nameof(RB_Contribute_Medium_ViewModel.UpdateTime), demodel.UpdateTime},
                    { nameof(RB_Contribute_Medium_ViewModel.MediaName), demodel.MediaName},
                };
                if (demodel.Type == ContributeMediumTypeEnum.Video)
                {
                    keyValues.Add(nameof(RB_Contribute_Medium_ViewModel.VideoWXImage), demodel.VideoWXImage);
                    keyValues.Add(nameof(RB_Contribute_Medium_ViewModel.Description), demodel.Description);
                }
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName = nameof(RB_Contribute_Medium_ViewModel.Id),
                          FiledValue = demodel.Id,
                           OperatorEnum = OperatorEnum.Equal
                    }
                };
                bool flag = contribute_MediumRepository.Update(keyValues, wheres);
                return flag ? "" : "出错了，请联系管理员";
            }
            else {
                #region 验证平台配置
                var configModel = contribute_ConfigRepository.GetList(new RB_Contribute_Config_ViewModel() { Group_Id = demodel.Group_Id, Type = demodel.PlatformType }).FirstOrDefault();
                if (configModel == null || configModel.Enable != 1) { return "平台配置未启用"; }
                #endregion
                demodel.Media_Id = "";
                int MediaId = contribute_MediumRepository.Insert(demodel);
                if (MediaId > 0) {
                    //上传素材至公众号  先同步  太慢的话 用任务处理
                    demodel.Id = MediaId;
                    string fileMsg = UploadMediumToGZH(demodel, configModel);
                    if (fileMsg != "") { return fileMsg; }
                }
                return MediaId > 0 ? "" : "出错了，请联系管理员";
            }
        }

        /// <summary>
        /// 上传文件至公众号
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        private string UploadMediumToGZH(RB_Contribute_Medium_ViewModel dmodel, RB_Contribute_Config_ViewModel configModel)
        {
            if (dmodel.PlatformType == ContributeConfigTypeEnum.Subscription)
            {
                #region 首先拉取临时文件
                if (dmodel.Path.Contains("http"))
                {
                    //获取服务器文件存至本地  每日定时器清理
                    string filePath = QYWeiXinHelper.CopyFileByUrl(dmodel.Path, Path.GetFileName(dmodel.Path));
                    dmodel.Path = filePath;
                }
                string vImagePath = "";
                if (!string.IsNullOrEmpty(dmodel.VideoImage) && dmodel.VideoImage.Contains("http"))
                {
                    vImagePath = QYWeiXinHelper.CopyFileByUrl(dmodel.VideoImage, Path.GetFileName(dmodel.VideoImage));
                    dmodel.VideoImage = vImagePath;
                }
                #endregion

                //获取公众号token
                string token = GetGZHToken(dmodel.Group_Id, configModel);
                if (string.IsNullOrEmpty(token))
                {
                    return "公众号token获取失败";
                }

                Dictionary<string, object> keyValues = new Dictionary<string, object>() { };

                if (dmodel.Type == ContributeMediumTypeEnum.Video)
                {
                    //视频  要多传标题+描述
                    try
                    {
                        var Rmsg = GZHWeChatHelper.UploadForeverVideo(token, dmodel.Path, dmodel.MediaName, dmodel.Description, "video");
                        if (Rmsg.errcode == Senparc.Weixin.ReturnCode.请求成功)
                        {
                            keyValues.Add(nameof(RB_Contribute_Medium_ViewModel.Media_Id), Rmsg.media_id);

                            //获取视频素材详情  拿取down_url
                            try
                            {
                                var GRmsg = GZHWeChatHelper.GetForeverVideo(token, Rmsg.media_id);
                                if (GRmsg.errcode == Senparc.Weixin.ReturnCode.请求成功)
                                {
                                    keyValues.Add(nameof(RB_Contribute_Medium_ViewModel.VideoWXPath), GRmsg.down_url);
                                }
                                else
                                {
                                    LogHelper.Write("获取视频素材失败，" + Rmsg.errmsg);
                                }
                            }
                            catch (Exception ex)
                            {
                                LogHelper.Write("获取视频素材失败，" + ex.Message);
                            }
                        }
                        else
                        {
                            LogHelper.Write("上传永久素材失败，" + Rmsg.errmsg);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Write("上传永久素材失败，" + ex.Message);
                    }

                    if (!string.IsNullOrEmpty(dmodel.VideoImage))
                    {
                        //视频封面图 缩略图
                        try
                        {
                            var Rmsg = GZHWeChatHelper.UploadForeverMedia(token, dmodel.VideoImage);
                            if (Rmsg.errcode == Senparc.Weixin.ReturnCode.请求成功)
                            {
                                keyValues.Add(nameof(RB_Contribute_Medium_ViewModel.VideoWXImage), Rmsg.url);
                            }
                            else
                            {
                                LogHelper.Write("上传视频素材封面图失败，" + Rmsg.errmsg);
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Write("上传视频素材封面图失败，" + ex.Message);
                        }
                    }
                }
                else if (dmodel.Type == ContributeMediumTypeEnum.Audio) {
                    //音频
                    try
                    {
                        var Rmsg = GZHWeChatHelper.UploadForeverVideo(token, dmodel.Path, dmodel.MediaName, dmodel.Description, "voice");
                        if (Rmsg.errcode == Senparc.Weixin.ReturnCode.请求成功)
                        {
                            keyValues.Add(nameof(RB_Contribute_Medium_ViewModel.Media_Id), Rmsg.media_id);
                        }
                        else
                        {
                            LogHelper.Write("上传永久素材失败，" + Rmsg.errmsg);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Write("上传永久素材失败，" + ex.Message);
                    }
                }
                else
                {
                    //图片 音频
                    try
                    {
                        var Rmsg = GZHWeChatHelper.UploadForeverMedia(token, dmodel.Path);
                        if (Rmsg.errcode == Senparc.Weixin.ReturnCode.请求成功)
                        {
                            keyValues.Add(nameof(RB_Contribute_Medium_ViewModel.Media_Id), Rmsg.media_id);
                            if (dmodel.Type == ContributeMediumTypeEnum.Image)
                            {
                                keyValues.Add(nameof(RB_Contribute_Medium_ViewModel.ImageUrl), Rmsg.url);
                            }
                        }
                        else
                        {
                            LogHelper.Write("上传永久素材失败，" + Rmsg.errmsg);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Write("上传永久素材失败，" + ex.Message);
                    }
                }

                keyValues.Add(nameof(RB_Contribute_Medium_ViewModel.UploadTime), DateTime.Now);//上传时间
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName = nameof(RB_Contribute_Medium_ViewModel.Id),
                          FiledValue = dmodel.Id,
                           OperatorEnum =OperatorEnum.Equal
                    }
                };
                contribute_MediumRepository.Update(keyValues, wheres);
                return "";
            }
            else {
                return "平台类型有误，上传失败";
            }
        }

        /// <summary>
        /// 获取公众号token
        /// </summary>
        /// <param name="Group_Id"></param>
        /// <param name="configmodel"></param>
        /// <returns></returns>
        private string GetGZHToken(int Group_Id, RB_Contribute_Config_ViewModel configmodel)
        {
            string token = WeChatReidsCache.GetToken(Cache.CacheKey.GZH_ZYSH_Key + Group_Id);
            if (string.IsNullOrEmpty(token))
            {
                try
                {
                    var TokenMsg = GZHWeChatHelper.GetGZHToken(configmodel.AppId, configmodel.AppSecret);
                    if (TokenMsg.errcode == Senparc.Weixin.ReturnCode.请求成功)
                    {
                        WeChatReidsCache.TokenSet(Cache.CacheKey.GZH_ZYSH_Key + Group_Id, TokenMsg.access_token, TokenMsg.expires_in - 1);
                        token = TokenMsg.access_token;
                    }
                    else
                    {
                        LogHelper.Write("公众号token获取失败，" + TokenMsg.errmsg);
                        return "";
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Write("公众号token获取失败，" + ex.Message);
                }
            }
            return token;
        }

        /// <summary>
        /// 获取启用的素材平台列表
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetContributePlatfromList(UserInfo userInfo)
        {
            var list = contribute_ConfigRepository.GetList(new RB_Contribute_Config_ViewModel() { Group_Id = userInfo.Group_Id, Enable = 1 });
            list = list.OrderBy(x => x.Type).ToList();
            return list.Select(x => new
            {
                Id = x.Type,
                Name = x.Type.ToName()
            });
        }

        /// <summary>
        /// 素材移动分组
        /// </summary>
        /// <param name="mediumIds"></param>
        /// <param name="mediumGroupId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetContributeMediumMoveGroup(string mediumIds, int mediumGroupId, UserInfo userInfo)
        {
            var list = contribute_MediumRepository.GetList(new RB_Contribute_Medium_ViewModel() { Group_Id = userInfo.Group_Id, MediumIds = mediumIds });
            var trans = contribute_MediumRepository.DbTransaction;
            try
            {
                foreach (var item in list)
                {
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Contribute_Medium_ViewModel.MediaGroupId), mediumGroupId},
                        { nameof(RB_Contribute_Medium_ViewModel.UpdateBy), userInfo.Id},
                        { nameof(RB_Contribute_Medium_ViewModel.UpdateTime), DateTime.Now},
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName = nameof(RB_Contribute_Medium_ViewModel.Id),
                              FiledValue = item.Id,
                               OperatorEnum = OperatorEnum.Equal
                        }
                    };
                    contribute_MediumRepository.Update(keyValues, wheres, trans);
                }
                contribute_MediumRepository.DBSession.Commit();
                return "";
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetContributeMediumMoveGroup");
                contribute_MediumRepository.DBSession.Rollback();
                return "出错了，请联系管理员";
            }            
        }

        /// <summary>
        /// 删除素材
        /// </summary>
        /// <param name="mediumIds"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string DelContributeMediumBatch(string mediumIds, UserInfo userInfo)
        {
            var list = contribute_MediumRepository.GetList(new RB_Contribute_Medium_ViewModel() { Group_Id = userInfo.Group_Id, MediumIds = mediumIds });
            if (!list.Any()) { return "没有可删除的数据"; }
            if (list.Select(x => x.PlatformType).Distinct().Count() > 1) { return "无法批量删除不同平台的素材"; }
            var type = list.FirstOrDefault().PlatformType;
            var configModel = contribute_ConfigRepository.GetList(new RB_Contribute_Config_ViewModel() { Group_Id = userInfo.Group_Id, Type = type }).FirstOrDefault();
            if (configModel == null || configModel.Enable != 1) { return "平台配置未启用"; }
            //获取公众号token
            string token = GetGZHToken(userInfo.Group_Id, configModel);
            if (string.IsNullOrEmpty(token))
            {
                return "公众号token获取失败";
            }

            var trans = contribute_MediumRepository.DbTransaction;
            try
            {
                foreach (var item in list)
                {
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Contribute_Medium_ViewModel.Status), 1},
                        { nameof(RB_Contribute_Medium_ViewModel.UpdateBy), userInfo.Id},
                        { nameof(RB_Contribute_Medium_ViewModel.UpdateTime), DateTime.Now},
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName = nameof(RB_Contribute_Medium_ViewModel.Id),
                              FiledValue = item.Id,
                               OperatorEnum = OperatorEnum.Equal
                        }
                    };
                    bool flag = contribute_MediumRepository.Update(keyValues, wheres, trans);
                    if (flag) {
                        if (item.PlatformType == ContributeConfigTypeEnum.Subscription && !string.IsNullOrEmpty(item.Media_Id)) {
                            //删除公众号素材
                            try
                            {
                                var Rmsg = GZHWeChatHelper.DeleteForeverMedia(token, item.Media_Id);
                                if (Rmsg.errcode != Senparc.Weixin.ReturnCode.请求成功)
                                {
                                    LogHelper.Write("删除公众号素材失败：" + item.Id + "、MediaId:" + item.Media_Id);
                                }
                            }
                            catch (Exception ex)
                            {
                                LogHelper.Write(ex, "删除公众号素材失败：" + item.Id + "、MediaId:" + item.Media_Id);
                            }
                        }
                    }
                }
                contribute_MediumRepository.DBSession.Commit();
                return "";
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetContributeMediumMoveGroup");
                contribute_MediumRepository.DBSession.Rollback();
                return "出错了，请联系管理员";
            }
        }

        /// <summary>
        /// 上传临时文件-图文素材 图片 至公众号
        /// </summary>
        /// <param name="path_server"></param>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public string UploadImageTextGetUrl(string path_server, int groupId, out bool flag)
        {
            flag = false;
            #region 验证平台配置
            var configModel = contribute_ConfigRepository.GetList(new RB_Contribute_Config_ViewModel() { Group_Id = groupId, Type = ContributeConfigTypeEnum.Subscription }).FirstOrDefault();
            if (configModel == null || configModel.Enable != 1) { return "平台配置未启用"; }
            #endregion

            //获取公众号token
            string token = GetGZHToken(groupId, configModel);
            if (string.IsNullOrEmpty(token))
            {
                return "公众号token获取失败";
            }

            //图片 音频
            try
            {
                var Rmsg = GZHWeChatHelper.UploadImg(token, path_server);
                if (Rmsg.errcode == Senparc.Weixin.ReturnCode.请求成功)
                {
                    flag = true;
                    return Rmsg.url;
                }
                else
                {
                    LogHelper.Write("上传永久素材失败，" + Rmsg.errmsg);
                    return "上传图片失败";
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write("上传永久素材失败，" + ex.Message);
                return "上传图片失败";
            }
        }


        /// <summary>
        /// 测试接口
        /// </summary>
        /// <returns></returns>
        public string Test() {

            //var configModel = contribute_ConfigRepository.GetList(new RB_Contribute_Config_ViewModel() { Group_Id = 100000, Type = ContributeConfigTypeEnum.Subscription }).FirstOrDefault();
            //if (configModel == null || configModel.Enable != 1) { return "平台配置未启用"; }
            //string token2 = GetGZHToken(100000, configModel);
            //LogHelper.Write(token2);
            string token = "50_mVuK5HbS0_w6mgPxp7Zdaza9h2Nlg4jiqxTZvHCWLfu1ZLaCCSKBZCrkm827tLWXDRB9FGVX-qUlXc6EtvJvciFJfz3Bjg1oa0A4J_-zQZMy9epaQxnOpJ_QbY4EmS-X5qvTyKN9SA490aIgTQEdADAHES";
            if (!string.IsNullOrEmpty(token))
            {
                try
                {
                    //var Rmsg = GZHWeChatHelper.UploadForeverMedia(token, "http://imgfile.oytour.com/Upload/Temporary/202110130619195430000000013.jpg");
                    //图片
                    //var Rmsg = GZHWeChatHelper.UploadForeverMedia(token, "C:\\Users\\Administrator\\Desktop\\testImage\\封面图\\QQ123123.jpg");
                    //视频
                    //var Rmsg = GZHWeChatHelper.UploadForeverVideo(token, "C:\\Users\\Administrator\\Desktop\\testImage\\视频文件\\微途科技公司\\xmm.mp4", "测试视频文件", "测试视频文件", "video");
                    //LogHelper.Write(JsonHelper.Serialize(Rmsg));
                    //音频
                    var Rmsg2 = GZHWeChatHelper.UploadForeverMedia(token, "C:\\Users\\Administrator\\Desktop\\testImage\\视频文件\\微途科技公司\\bzdsazi.mp3");
                    LogHelper.Write(JsonHelper.Serialize(Rmsg2));
                }
                catch (Exception ex)
                {
                    return "上传永久素材失败，" + ex.Message;
                }
            }
            return "";
        }
        #endregion

        #region 投稿管理

        /// <summary>
        /// 获取投稿分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Contribute_Info_ViewModel> GetContributeInfoPageList(int pageIndex, int pageSize, out long count, RB_Contribute_Info_ViewModel demodel)
        {
            var list = contribute_InfoRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any()) {
                List<int> MeadiumIds = new List<int>();
                if (list.Where(x => x.CoverImageId > 0).Any()) {
                    MeadiumIds.AddRange(list.Where(x => x.CoverImageId > 0).Select(x => x.CoverImageId).Distinct());
                }
                if (list.Where(x => x.VideoMediumId > 0).Any()) {
                    MeadiumIds.AddRange(list.Where(x => x.VideoMediumId > 0).Select(x => x.VideoMediumId).Distinct());
                }
                if (list.Where(x => !string.IsNullOrEmpty(x.ImageMediumIds)).Any()) {
                    foreach (var item in list.Where(x => !string.IsNullOrEmpty(x.ImageMediumIds))) {
                        MeadiumIds.AddRange(JsonHelper.DeserializeObject<List<int>>("[" + item.ImageMediumIds + "]"));
                    }
                }
                List<RB_Contribute_Medium_ViewModel> mediumList = new List<RB_Contribute_Medium_ViewModel>();
                if (MeadiumIds.Any()) {
                    mediumList = contribute_MediumRepository.GetList(new RB_Contribute_Medium_ViewModel() { Group_Id = demodel.Group_Id, MediumIds = string.Join(",", MeadiumIds.Distinct()) });
                }

                foreach (var item in list) {
                    if (item.CoverImageId > 0) {
                        item.CoverImagePath = mediumList.Where(x => x.Id == item.CoverImageId).FirstOrDefault()?.ImageUrl ?? "";
                    }
                    if (item.VideoMediumId > 0) {
                        var mediumModel = mediumList.Where(x => x.Id == item.VideoMediumId).FirstOrDefault();
                        item.VideoMediumPath = mediumModel?.Path ?? "";
                        if (item.Type == ContributeInfoTypeEnum.Video) {
                            item.VideoCoverImage = mediumModel?.VideoWXImage ?? "";
                        }
                    }
                    item.ImageList = new List<RB_Contribute_Medium_ViewModel>();
                    if (!string.IsNullOrEmpty(item.ImageMediumIds)) {
                        item.ImageList = mediumList.Where(x => ("," + item.ImageMediumIds + ",").Contains("," + x.Id + ",")).ToList();
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取投稿信息
        /// </summary>
        /// <param name="contributeId"></param>
        /// <returns></returns>
        public RB_Contribute_Info_ViewModel GetContributeInfo(int contributeId, int groupId)
        {
            var model = contribute_InfoRepository.GetEntity<RB_Contribute_Info_ViewModel>(contributeId);
            if (model != null) {
                List<int> MeadiumIds = new List<int>();
                if (model.CoverImageId >0)
                {
                    MeadiumIds.Add(model.CoverImageId);
                }
                if (model.VideoMediumId > 0)
                {
                    MeadiumIds.Add(model.VideoMediumId);
                }
                if (!string.IsNullOrEmpty(model.ImageMediumIds))
                {
                    MeadiumIds.AddRange(JsonHelper.DeserializeObject<List<int>>("[" + model.ImageMediumIds + "]"));
                }
                List<RB_Contribute_Medium_ViewModel> mediumList = new List<RB_Contribute_Medium_ViewModel>();
                if (MeadiumIds.Any())
                {
                    mediumList = contribute_MediumRepository.GetList(new RB_Contribute_Medium_ViewModel() { Group_Id = groupId, MediumIds = string.Join(",", MeadiumIds.Distinct()) });
                }

                if (model.CoverImageId > 0)
                {
                    model.CoverImagePath = mediumList.Where(x => x.Id == model.CoverImageId).FirstOrDefault()?.ImageUrl ?? "";
                }
                if (model.VideoMediumId > 0)
                {
                    var mediumModel = mediumList.Where(x => x.Id == model.VideoMediumId).FirstOrDefault();
                    model.VideoMediumPath = mediumModel?.Path ?? "";
                    if (model.Type == ContributeInfoTypeEnum.Video)
                    {
                        model.VideoCoverImage = mediumModel?.VideoWXImage ?? "";
                    }
                }
                model.ImageList = new List<RB_Contribute_Medium_ViewModel>();
                if (!string.IsNullOrEmpty(model.ImageMediumIds))
                {
                    model.ImageList = mediumList.Where(x => ("," + model.ImageMediumIds + ",").Contains("," + x.Id + ",")).ToList();
                }
            }
            return model;
        }

        /// <summary>
        /// 新增修改投稿
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetContributeInfo(RB_Contribute_Info_ViewModel demodel)
        {
            bool flag;
            if (demodel.Id > 0)
            {
                var oldModel = contribute_InfoRepository.GetEntity(demodel.Id);
                if (oldModel == null || oldModel.Status == 1) { return "投稿不存在"; }
                if (oldModel.AuditState != ContributeInfoStateEnum.Temporary && oldModel.AuditState != ContributeInfoStateEnum.Reject) { return "状态不正确,无法修改"; }
                if (oldModel.CreateBy != demodel.CreateBy) { return "不是您创建的投稿，无法修改"; }
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Contribute_Info_ViewModel.CoverImageId), demodel.CoverImageId},
                    { nameof(RB_Contribute_Info_ViewModel.Title), demodel.Title},
                    { nameof(RB_Contribute_Info_ViewModel.Author), demodel.Author},
                    { nameof(RB_Contribute_Info_ViewModel.Description), demodel.Description},
                    { nameof(RB_Contribute_Info_ViewModel.Content), demodel.Content},
                    { nameof(RB_Contribute_Info_ViewModel.SendContent), demodel.SendContent},
                    { nameof(RB_Contribute_Info_ViewModel.VideoMediumId), demodel.VideoMediumId},
                    { nameof(RB_Contribute_Info_ViewModel.ImageMediumIds), demodel.ImageMediumIds},
                    { nameof(RB_Contribute_Info_ViewModel.AuditState), demodel.AuditState},
                    { nameof(RB_Contribute_Info_ViewModel.UpdateBy), demodel.UpdateBy},
                    { nameof(RB_Contribute_Info_ViewModel.UpdateTime), demodel.UpdateTime},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName = nameof(RB_Contribute_Info_ViewModel.Id),
                          FiledValue = demodel.Id,
                           OperatorEnum =OperatorEnum.Equal
                    }
                };
                var trans = contribute_InfoRepository.DbTransaction;
                try
                {
                    flag = contribute_InfoRepository.Update(keyValues, wheres, trans);
                    if (flag && demodel.AuditState == ContributeInfoStateEnum.Auditing && oldModel.AuditState == ContributeInfoStateEnum.Temporary)
                    {
                        //创建审核流程
                        flag = education_ReceiptRepository.SetEducationReceiptRepository(new RB_Education_Receipt()
                        {
                            Id = 0,
                            Title = "投稿单据",
                            ReceiptType = Common.Enum.Finance.ReceiptTypeEnum.Contribute,
                            RelationId = demodel.Id,
                            Group_Id = demodel.Group_Id,
                            School_Id = demodel.School_Id,
                            CreateBy = demodel.CreateBy,
                            CreateTime = DateTime.Now,
                            UpdateBy = demodel.UpdateBy,
                            UpdateTime = DateTime.Now,
                            RecipientIds = "",
                            VerifyStatus = Common.Enum.EduTask.EduTaskRrocessStatus.NotAudit,
                            ReceiptFile = ""
                        }, out string message);
                        if (flag == false)
                        {
                            contribute_InfoRepository.DBSession.Rollback();
                            return message;
                        }
                    }
                    contribute_InfoRepository.DBSession.Commit();
                    if (flag) {
                        contribute_InfoLogRepository.Insert(new Model.Entity.WeChat.RB_Contribute_InfoLog()
                        {
                            Id = 0,
                            ContributeId = demodel.Id,
                            CreateBy = demodel.CreateBy,
                            CreateTime = DateTime.Now,
                            Description = demodel.AuditState == ContributeInfoStateEnum.Auditing ? "修改投稿,并提交审核" : "修改投稿",
                            Group_Id = demodel.Group_Id,
                            Record = "",
                            Status = 0
                        });
                    }
                    return flag ? "" : "出错了，请联系管理员";
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "SetContributeInfo");
                    contribute_InfoRepository.DBSession.Rollback();
                    return "出错了，请联系管理员";
                }
            }
            else {
                var trans = contribute_InfoRepository.DbTransaction;
                try
                {
                    int ContributeId = contribute_InfoRepository.Insert(demodel, trans);
                    flag = ContributeId > 0;
                    if (flag && demodel.AuditState == ContributeInfoStateEnum.Auditing)
                    {
                        //创建审核流程~
                        flag = education_ReceiptRepository.SetEducationReceiptRepository(new RB_Education_Receipt()
                        {
                            Id = 0,
                            Title = "投稿单据",
                            ReceiptType = Common.Enum.Finance.ReceiptTypeEnum.Contribute,
                            RelationId = ContributeId,
                            Group_Id = demodel.Group_Id,
                            School_Id = demodel.School_Id,
                            CreateBy = demodel.CreateBy,
                            CreateTime = DateTime.Now,
                            UpdateBy = demodel.UpdateBy,
                            UpdateTime = DateTime.Now,
                            RecipientIds = "",
                            VerifyStatus = Common.Enum.EduTask.EduTaskRrocessStatus.NotAudit,
                            ReceiptFile = ""
                        }, out string message);
                        if (flag == false)
                        {
                            contribute_InfoRepository.DBSession.Rollback();
                            return message;
                        }
                    }
                    if (flag) {
                        contribute_InfoLogRepository.Insert(new Model.Entity.WeChat.RB_Contribute_InfoLog()
                        {
                            Id = 0,
                            ContributeId = ContributeId,
                            CreateBy = demodel.CreateBy,
                            CreateTime = DateTime.Now,
                            Description = demodel.AuditState == ContributeInfoStateEnum.Auditing ? "新增投稿,并提交审核" : "新增投稿",
                            Group_Id = demodel.Group_Id,
                            Record = "",
                            Status = 0
                        });
                    }
                    contribute_InfoRepository.DBSession.Commit();
                    return flag ? "" : "出错了，请联系管理员";
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "SetContributeInfo");
                    contribute_InfoRepository.DBSession.Rollback();
                    return "出错了，请联系管理员";
                }                
            }
        }

        /// <summary>
        /// 设置投稿状态
        /// </summary>
        /// <param name="contributeId"></param>
        /// <param name="type"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetContributeInfoState(int contributeId, int type, UserInfo userInfo)
        {
            var model = contribute_InfoRepository.GetEntity(contributeId);
            if (model == null || model.Status == 1) { return "投稿不存在"; }
            if (model.AuditState != ContributeInfoStateEnum.Temporary && model.AuditState != ContributeInfoStateEnum.Reject)
            {
                return "状态不正确";
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Contribute_Info_ViewModel.UpdateBy), userInfo.Id},
                { nameof(RB_Contribute_Info_ViewModel.UpdateTime), DateTime.Now}
            };
            if (type == 1)
            {
                //提交审核
                keyValues.Add(nameof(RB_Contribute_Info_ViewModel.AuditState), ContributeInfoStateEnum.Auditing);
            }
            else if (type == 2)
            {
                //删除
                keyValues.Add(nameof(RB_Contribute_Info_ViewModel.Status), 1);
            }
            else {
                return "type有误";
            }
            List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName = nameof(RB_Contribute_Info_ViewModel.Id),
                          FiledValue = contributeId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
            var trans = contribute_InfoRepository.DbTransaction;
            try
            {
                var flag = contribute_InfoRepository.Update(keyValues, wheres, trans);
                if (flag && type == 1)
                {
                    //创建审核流程
                    flag = education_ReceiptRepository.SetEducationReceiptRepository(new RB_Education_Receipt()
                    {
                        Id = 0,
                        Title = "投稿单据",
                        ReceiptType = Common.Enum.Finance.ReceiptTypeEnum.Contribute,
                        RelationId = contributeId,
                        Group_Id = model.Group_Id,
                        School_Id = model.School_Id,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        UpdateBy = userInfo.Id,
                        UpdateTime = DateTime.Now,
                        RecipientIds = "",
                        VerifyStatus = Common.Enum.EduTask.EduTaskRrocessStatus.NotAudit,
                        ReceiptFile = ""
                    }, out string message);
                    if (flag == false) {
                        contribute_InfoRepository.DBSession.Rollback();
                        return message; 
                    }
                }
                contribute_InfoRepository.DBSession.Commit();
                if (flag) {
                    contribute_InfoLogRepository.Insert(new Model.Entity.WeChat.RB_Contribute_InfoLog()
                    {
                        Id = 0,
                        ContributeId = contributeId,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Description = type == 1 ? "提交审核" : "删除投稿",
                        Group_Id = userInfo.Group_Id,
                        Record = "",
                        Status = 0
                    });
                }
                return flag ? "" : "出错了，请联系管理员";
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetContributeInfoState");
                contribute_InfoRepository.DBSession.Rollback();
                return "出错了，请联系管理员";
            }
        }

        /// <summary>
        /// 设置投稿发放
        /// </summary>
        /// <param name="contributeId"></param>
        /// <param name="remunerationState"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetRemunerationState(int contributeId, int remunerationState, UserInfo userInfo)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Contribute_Info_ViewModel.RemunerationState), remunerationState},
                { nameof(RB_Contribute_Info_ViewModel.UpdateBy), userInfo.Id},
                { nameof(RB_Contribute_Info_ViewModel.UpdateTime), DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName = nameof(RB_Contribute_Info_ViewModel.Id),
                        FiledValue = contributeId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = contribute_InfoRepository.Update(keyValues, wheres);
            return flag ? "" : "出错了，请联系管理员";
        }
        #endregion

        #region 小程序信息

        /// <summary>
        /// 获取小程序信息分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Contribute_Applet_ViewModel> GetContributeAppletPageList(int pageIndex, int pageSize, out long count, RB_Contribute_Applet_ViewModel demodel)
        {
            return contribute_AppletRepository.GetPageList(pageIndex, pageSize, out count, demodel);
        }

        /// <summary>
        /// 获取小程序列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Contribute_Applet_ViewModel> GetContributeAppletList(RB_Contribute_Applet_ViewModel demodel)
        {
            return contribute_AppletRepository.GetList(demodel);
        }

        /// <summary>
        /// 新增修改小程序
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetContributeApplet(RB_Contribute_Applet_ViewModel demodel)
        {
            bool flag;
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Contribute_Applet_ViewModel.Name), demodel.Name},
                    { nameof(RB_Contribute_Applet_ViewModel.AppID), demodel.AppID},
                    { nameof(RB_Contribute_Applet_ViewModel.Image), demodel.Image},
                    { nameof(RB_Contribute_Applet_ViewModel.Page), demodel.Page},
                    { nameof(RB_Contribute_Applet_ViewModel.UpdateBy), demodel.UpdateBy},
                    { nameof(RB_Contribute_Applet_ViewModel.UpdateTime), demodel.UpdateTime},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName = nameof(RB_Contribute_Applet_ViewModel.Id),
                          FiledValue = demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                flag = contribute_AppletRepository.Update(keyValues, wheres);
            }
            else {
                flag = contribute_AppletRepository.Insert(demodel) > 0;
            }
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 删除小程序信息
        /// </summary>
        /// <param name="appletId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string DelContributeApplet(int appletId, UserInfo userInfo)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Contribute_Applet_ViewModel.Status), 1},   
                { nameof(RB_Contribute_Applet_ViewModel.UpdateBy), userInfo.Id},
                { nameof(RB_Contribute_Applet_ViewModel.UpdateTime), DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName = nameof(RB_Contribute_Applet_ViewModel.Id),
                          FiledValue = appletId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
            var flag = contribute_AppletRepository.Update(keyValues, wheres);
            return flag ? "" : "出错了，请联系管理员";
        }

        #endregion

        #region 发布投稿
        /// <summary>
        /// 发布
        /// </summary>
        /// <param name="contributeId"></param>
        /// <param name="platformId"></param>
        /// <param name="IsPreview">1预览  2群发</param>
        /// <param name="tagId">用户标签 / 微信号(预览时使用)</param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetContributeInfoPublish(int contributeId, int platformId, int IsPreview, string tagId, UserInfo userInfo)
        {
            var model = contribute_InfoRepository.GetEntity(contributeId);
            if (model.AuditState != ContributeInfoStateEnum.Audited) {
                return "未审核通过，无法发布";
            }

            #region 验证平台配置
            var configModel = contribute_ConfigRepository.GetList(new RB_Contribute_Config_ViewModel() { Group_Id = userInfo.Group_Id, Type = (ContributeConfigTypeEnum)platformId }).FirstOrDefault();
            if (configModel == null || configModel.Enable != 1) { return "平台配置未启用"; }
            #endregion
            if (configModel.Type == ContributeConfigTypeEnum.Subscription)
            {
                //获取公众号token
                string token = GetGZHToken(userInfo.Group_Id, configModel);
                if (string.IsNullOrEmpty(token))
                {
                    return "公众号token获取失败";
                }

                string Media_Id = "";
                int PublishLogId = 0;
                Senparc.Weixin.MP.GroupMessageType PType = Senparc.Weixin.MP.GroupMessageType.mpnews;
                if (model.Type == ContributeInfoTypeEnum.ImgText)
                {
                    string thumb_media_id = "";
                    if (model.Type == ContributeInfoTypeEnum.ImgText && model.CoverImageId > 0)
                    {
                        thumb_media_id = contribute_MediumRepository.GetEntity(model.CoverImageId)?.Media_Id ?? "";
                    }
                    NewsModel newsModel = new NewsModel()
                    {
                        author = model.Author,
                        content = model.SendContent,
                        content_source_url = model.SourceUrl,
                        digest = model.Description,
                        need_open_comment = model.IsOpenComment,
                        only_fans_can_comment = model.IsFansCanComment,
                        show_cover_pic = model.IsShowCover.ToString(),
                        title = model.Title,
                        thumb_media_id = thumb_media_id,
                        thumb_url = ""
                    };
                    //查询该平台是否已发布过
                    var pmodel = contribute_PublishLogRepository.GetList(new RB_Contribute_PublishLog_ViewModel() { Group_Id = userInfo.Group_Id, ContributeId = contributeId, PlatfromId = (ContributeConfigTypeEnum)platformId }).FirstOrDefault();
                    if (pmodel == null)
                    {
                        //新增图文
                        var nlist = new List<NewsModel>() { newsModel };
                        try
                        {
                            var Rmsg = GZHWeChatHelper.UploadNews(token, nlist.ToArray());
                            if (Rmsg.errcode == Senparc.Weixin.ReturnCode.请求成功)
                            {
                                Media_Id = Rmsg.media_id;
                                //新增平台发布
                                PublishLogId = contribute_PublishLogRepository.Insert(new Model.Entity.WeChat.RB_Contribute_PublishLog()
                                {
                                    Id = 0,
                                    Content = "发布图文素材",
                                    ContributeId = contributeId,
                                    CreateBy = userInfo.Id,
                                    CreateTime = DateTime.Now,
                                    Group_Id = userInfo.Group_Id,
                                    Media_Id = Media_Id,
                                    PlatfromId = configModel.Type,
                                    Status = 0,
                                    UpdateBy = userInfo.Id,
                                    UpdateTime = DateTime.Now
                                });
                            }
                            else
                            {
                                LogHelper.Write("新增图文素材失败：" + Rmsg.errmsg);
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Write("新增图文素材失败：" + ex.Message);
                        }
                    }
                    else
                    {
                        PublishLogId = pmodel.Id;
                        //修改图文
                        try
                        {
                            var Rmsg = GZHWeChatHelper.UpdateForeverNews(token, pmodel.Media_Id, 0, newsModel);
                            if (Rmsg.errcode == Senparc.Weixin.ReturnCode.请求成功)
                            {
                                //修改成功
                                Media_Id = pmodel.Media_Id;
                            }
                            else
                            {
                                LogHelper.Write("修改图文素材失败：" + Rmsg.errmsg);
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Write("修改图文素材失败：" + ex.Message);
                        }
                    }
                }
                else if (model.Type == ContributeInfoTypeEnum.Video)
                {
                    PType = Senparc.Weixin.MP.GroupMessageType.video;
                    //查询该平台是否已发布过
                    var pmodel = contribute_PublishLogRepository.GetList(new RB_Contribute_PublishLog_ViewModel() { Group_Id = userInfo.Group_Id, ContributeId = contributeId, PlatfromId = (ContributeConfigTypeEnum)platformId }).FirstOrDefault();
                    if (pmodel == null)
                    {
                        string mediumId = contribute_MediumRepository.GetEntity(model.VideoMediumId)?.Media_Id ?? "";
                        try
                        {
                            var Rmsg = GZHWeChatHelper.GetVideoMediaIdResult(token, mediumId, model.Title, model.Description);
                            if (Rmsg.errcode == Senparc.Weixin.ReturnCode.请求成功)
                            {
                                Media_Id = Rmsg.media_id;
                                //新增平台发布
                                PublishLogId = contribute_PublishLogRepository.Insert(new Model.Entity.WeChat.RB_Contribute_PublishLog()
                                {
                                    Id = 0,
                                    Content = "新增视频发布",
                                    ContributeId = contributeId,
                                    CreateBy = userInfo.Id,
                                    CreateTime = DateTime.Now,
                                    Group_Id = userInfo.Group_Id,
                                    Media_Id = Media_Id,
                                    PlatfromId = configModel.Type,
                                    Status = 0,
                                    UpdateBy = userInfo.Id,
                                    UpdateTime = DateTime.Now
                                });
                            }
                            else
                            {
                                LogHelper.Write("新增视频发布失败：" + Rmsg.errmsg);
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Write("新增视频发布失败：" + ex.Message);
                        }
                    }
                    else
                    {
                        PublishLogId = pmodel.Id;
                        try
                        {
                            var Rmsg = GZHWeChatHelper.GetVideoMediaIdResult(token, pmodel.Media_Id, model.Title, model.Description);
                            if (Rmsg.errcode == Senparc.Weixin.ReturnCode.请求成功)
                            {
                                //修改成功
                                Media_Id = pmodel.Media_Id;
                            }
                            else
                            {
                                LogHelper.Write("修改视频发布失败：" + Rmsg.errmsg);
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Write("修改视频发布失败：" + ex.Message);
                        }
                    }
                }
                else if (model.Type == ContributeInfoTypeEnum.Audio)
                {
                    PType = Senparc.Weixin.MP.GroupMessageType.voice;
                    Media_Id = contribute_MediumRepository.GetEntity(model.VideoMediumId)?.Media_Id ?? "";
                    //查询该平台是否已发布过
                    var pmodel = contribute_PublishLogRepository.GetList(new RB_Contribute_PublishLog_ViewModel() { Group_Id = userInfo.Group_Id, ContributeId = contributeId, PlatfromId = (ContributeConfigTypeEnum)platformId }).FirstOrDefault();
                    if (pmodel == null)
                    {
                        PublishLogId = contribute_PublishLogRepository.Insert(new Model.Entity.WeChat.RB_Contribute_PublishLog()
                        {
                            Id = 0,
                            Content = "新增音频发布",
                            ContributeId = contributeId,
                            CreateBy = userInfo.Id,
                            CreateTime = DateTime.Now,
                            Group_Id = userInfo.Group_Id,
                            Media_Id = Media_Id,
                            PlatfromId = configModel.Type,
                            Status = 0,
                            UpdateBy = userInfo.Id,
                            UpdateTime = DateTime.Now
                        });
                    }
                    else
                    {
                        PublishLogId = pmodel.Id;
                    }
                }
                else if (model.Type == ContributeInfoTypeEnum.Text)
                {
                    PType = Senparc.Weixin.MP.GroupMessageType.text;
                    Media_Id = model.Description;
                    //查询该平台是否已发布过
                    var pmodel = contribute_PublishLogRepository.GetList(new RB_Contribute_PublishLog_ViewModel() { Group_Id = userInfo.Group_Id, ContributeId = contributeId, PlatfromId = (ContributeConfigTypeEnum)platformId }).FirstOrDefault();
                    if (pmodel == null)
                    {
                        PublishLogId = contribute_PublishLogRepository.Insert(new Model.Entity.WeChat.RB_Contribute_PublishLog()
                        {
                            Id = 0,
                            Content = "新增文本发布：",
                            ContributeId = contributeId,
                            CreateBy = userInfo.Id,
                            CreateTime = DateTime.Now,
                            Group_Id = userInfo.Group_Id,
                            Media_Id = "",
                            PlatfromId = configModel.Type,
                            Status = 0,
                            UpdateBy = userInfo.Id,
                            UpdateTime = DateTime.Now
                        });
                    }
                    else
                    {
                        PublishLogId = pmodel.Id;
                    }
                }
                else if (model.Type == ContributeInfoTypeEnum.Image)
                {
                    //图片  自己写推送方法  盛派不支持多图片
                    var mediumList = contribute_MediumRepository.GetList(new RB_Contribute_Medium_ViewModel() { Group_Id = userInfo.Group_Id, MediumIds = model.ImageMediumIds });
                    List<int> midsList = JsonHelper.DeserializeObject<List<int>>("[" + model.ImageMediumIds + "]");
                    List<string> wxMediaId = new List<string>();
                    foreach (var item in midsList)
                    {
                        string mediaId = mediumList.Where(x => x.Id == item).FirstOrDefault()?.Media_Id ?? "";
                        if (!string.IsNullOrEmpty(mediaId))
                        {
                            wxMediaId.Add(mediaId);
                        }
                    }
                    if (wxMediaId.Any())
                    {
                        var pmodel = contribute_PublishLogRepository.GetList(new RB_Contribute_PublishLog_ViewModel() { Group_Id = userInfo.Group_Id, ContributeId = contributeId, PlatfromId = (ContributeConfigTypeEnum)platformId }).FirstOrDefault();
                        if (pmodel == null)
                        {
                            PublishLogId = contribute_PublishLogRepository.Insert(new Model.Entity.WeChat.RB_Contribute_PublishLog()
                            {
                                Id = 0,
                                Content = "新增图片发布：" + model.Description,
                                ContributeId = contributeId,
                                CreateBy = userInfo.Id,
                                CreateTime = DateTime.Now,
                                Group_Id = userInfo.Group_Id,
                                Media_Id = Media_Id,
                                PlatfromId = configModel.Type,
                                Status = 0,
                                UpdateBy = userInfo.Id,
                                UpdateTime = DateTime.Now
                            });
                        }
                        else
                        {
                            PublishLogId = pmodel.Id;
                        }

                        if (IsPreview == 1)
                        {//预览
                            var Rmsg = GZHWeChatHelper.SendImageMessagePreview(token, tagId, wxMediaId.FirstOrDefault(), model.Description);
                            if (Rmsg != null && Rmsg.errcode == Senparc.Weixin.ReturnCode.请求成功)
                            {
                                //推送OK

                            }
                            else
                            {
                                //推送失败
                                LogHelper.Write("推送群发图文消息失败：" + Rmsg.errmsg);
                                return "推送失败，请联系管理员";
                            }
                        }
                        else if (IsPreview == 2)
                        {//群发
                            var Rmsg = GZHWeChatHelper.SendImageMessageByTagId(token, tagId, wxMediaId, model.Description, string.IsNullOrEmpty(tagId) ? true : false);
                            if (Rmsg != null && Rmsg.errcode == Senparc.Weixin.ReturnCode.请求成功)
                            {
                                //推送OK
                                if (PublishLogId > 0)
                                {
                                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                        { nameof(RB_Contribute_PublishLog_ViewModel.Msg_Id), Rmsg.msg_id},
                                        { nameof(RB_Contribute_PublishLog_ViewModel.Msg_Data_Id), Rmsg.msg_data_id},
                                    };
                                    List<WhereHelper> wheres = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName = nameof(RB_Contribute_PublishLog_ViewModel.Id),
                                              FiledValue = PublishLogId,
                                               OperatorEnum = OperatorEnum.Equal
                                        }
                                    };
                                    contribute_PublishLogRepository.Update(keyValues, wheres);
                                }
                            }
                            else
                            {
                                //推送失败
                                LogHelper.Write("推送群发图文消息失败：" + Rmsg.errmsg);
                                return "推送失败，请联系管理员";
                            }
                        }
                    }
                }

                if (!string.IsNullOrEmpty(Media_Id))
                {
                    //开始群发推送
                    try
                    {
                        if (IsPreview == 1)
                        {
                            //预览接口
                            var Rmsg = GZHWeChatHelper.SendGroupMessagePreview(token, PType, Media_Id, "", tagId);
                            if (Rmsg.errcode == Senparc.Weixin.ReturnCode.请求成功)
                            {
                                //推送OK

                            }
                            else
                            {
                                //推送失败
                                LogHelper.Write("推送群发图文消息失败：" + Rmsg.errmsg);
                                return "推送失败，请联系管理员";
                            }
                        }
                        else if (IsPreview == 2)
                        {
                            //群发
                            var Rmsg = GZHWeChatHelper.SendGroupMessageByTagId(token, tagId, Media_Id, PType, string.IsNullOrEmpty(tagId) ? true : false);
                            if (Rmsg.errcode == Senparc.Weixin.ReturnCode.请求成功)
                            {
                                //推送OK  需要记录推送的 Msg_Id 以后用作查询使用
                                if (PublishLogId > 0)
                                {
                                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                        { nameof(RB_Contribute_PublishLog_ViewModel.Msg_Id), Rmsg.msg_id},
                                        { nameof(RB_Contribute_PublishLog_ViewModel.Msg_Data_Id), Rmsg.msg_data_id},
                                        { nameof(RB_Contribute_PublishLog_ViewModel.UpdateTime), DateTime.Now}
                                    };
                                    List<WhereHelper> wheres = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName = nameof(RB_Contribute_PublishLog_ViewModel.Id),
                                              FiledValue = PublishLogId,
                                               OperatorEnum = OperatorEnum.Equal
                                        }
                                    };
                                    contribute_PublishLogRepository.Update(keyValues, wheres);
                                }
                            }
                            else
                            {
                                //推送失败
                                LogHelper.Write("推送群发图文消息失败：" + Rmsg.errmsg);
                                return "推送失败，请联系管理员";
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Write("推送群发图文消息失败：" + ex.Message);
                        return "推送失败，请联系管理员";
                    }
                }
            }
            else if (configModel.Type == ContributeConfigTypeEnum.Other) {
                //查询该平台是否已发布过
                var pmodel = contribute_PublishLogRepository.GetList(new RB_Contribute_PublishLog_ViewModel() { Group_Id = userInfo.Group_Id, ContributeId = contributeId, PlatfromId = (ContributeConfigTypeEnum)platformId }).FirstOrDefault();
                if (pmodel == null)
                {
                    contribute_PublishLogRepository.Insert(new Model.Entity.WeChat.RB_Contribute_PublishLog()
                    {
                        Id = 0,
                        Content = "发布其他平台",
                        ContributeId = contributeId,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        Media_Id = "",
                        PlatfromId = configModel.Type,
                        Status = 0,
                        UpdateBy = userInfo.Id,
                        UpdateTime = DateTime.Now
                    });
                }
            }
            else
            {
                return "该平台未开通";
            }
            return "";
        }

        /// <summary>
        /// 新增修改投稿
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetAdminContributeInfo(RB_Contribute_Info_ViewModel demodel, UserInfo userInfo)
        {
            if (demodel.Id > 0)
            {
                var oldModel = contribute_InfoRepository.GetEntity(demodel.Id);
                if (oldModel == null || oldModel.Status == 1) { return "投稿不存在"; }
                if (oldModel.AuditState != ContributeInfoStateEnum.Audited) { return "状态不正确,无法修改"; }
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Contribute_Info_ViewModel.CoverImageId), demodel.CoverImageId},
                    { nameof(RB_Contribute_Info_ViewModel.Title), demodel.Title},
                    { nameof(RB_Contribute_Info_ViewModel.Author), demodel.Author},
                    { nameof(RB_Contribute_Info_ViewModel.Description), demodel.Description},
                    { nameof(RB_Contribute_Info_ViewModel.Content), demodel.Content},
                    { nameof(RB_Contribute_Info_ViewModel.SendContent), demodel.SendContent},
                    { nameof(RB_Contribute_Info_ViewModel.VideoMediumId), demodel.VideoMediumId},
                    { nameof(RB_Contribute_Info_ViewModel.ImageMediumIds), demodel.ImageMediumIds},
                    { nameof(RB_Contribute_Info_ViewModel.AuditState), demodel.AuditState},
                    { nameof(RB_Contribute_Info_ViewModel.UpdateBy), demodel.UpdateBy},
                    { nameof(RB_Contribute_Info_ViewModel.UpdateTime), demodel.UpdateTime},
                    { nameof(RB_Contribute_Info_ViewModel.IsShowCover), demodel.IsShowCover},
                    { nameof(RB_Contribute_Info_ViewModel.IsOpenComment), demodel.IsOpenComment},
                    { nameof(RB_Contribute_Info_ViewModel.IsFansCanComment), demodel.IsFansCanComment},
                    { nameof(RB_Contribute_Info_ViewModel.SourceUrl), demodel.SourceUrl},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName = nameof(RB_Contribute_Info_ViewModel.Id),
                          FiledValue = demodel.Id,
                           OperatorEnum =OperatorEnum.Equal
                    }
                };
                var flag = contribute_InfoRepository.Update(keyValues, wheres);
                if (flag) {
                    //记录管理端操作日志
                    contribute_InfoLogRepository.Insert(new Model.Entity.WeChat.RB_Contribute_InfoLog()
                    {
                        Id = 0,
                        ContributeId = demodel.Id,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Description = "管理端修改投稿",
                        Group_Id = userInfo.Group_Id,
                        Record = JsonHelper.Serialize(oldModel),
                        Status = 0
                    });

                    if (demodel.IsPreview > 0) {
                        string rmsg = SetContributeInfoPublish(demodel.Id, demodel.PlatformId, demodel.IsPreview, demodel.TagId, userInfo);
                        if (rmsg != "") {
                            return rmsg;
                        }
                    }
                }
                return flag ? "" : "出错了，请联系管理员";
            }
            else
            {
                return "管理端无法新增";
            }
        }

        /// <summary>
        /// 获取微信公众号用户标签
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetGZHUserTagList(UserInfo userInfo, out bool flag)
        {
            flag = false;
            #region 验证平台配置
            var configModel = contribute_ConfigRepository.GetList(new RB_Contribute_Config_ViewModel() { Group_Id = userInfo.Group_Id, Type = ContributeConfigTypeEnum.Subscription }).FirstOrDefault();
            if (configModel == null || configModel.Enable != 1) { return "平台配置未启用"; }
            #endregion

            //获取公众号token
            string token = GetGZHToken(userInfo.Group_Id, configModel);
            if (string.IsNullOrEmpty(token))
            {
                return "公众号token获取失败";
            }

            try
            {
                var Rmsg = GZHWeChatHelper.GetUserTagList(token);
                if (Rmsg.errcode == Senparc.Weixin.ReturnCode.请求成功)
                {
                    flag = true;
                    return Rmsg.tags.Select(x => new
                    {
                        x.id,
                        x.name
                    });
                }
                else
                {
                    LogHelper.Write("获取公众号用户标签失败：" + Rmsg.errmsg);
                    return "获取标签失败，请联系管理员";
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "GetGZHUserTagList");
                return "出错了，请联系管理员";
            }
        }

        /// <summary>
        /// 获取发布记录
        /// </summary>
        /// <param name="contributeId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public List<RB_Contribute_PublishLog_ViewModel> GetContributeInfoPublishLogList(int contributeId, UserInfo userInfo)
        {
            var list = contribute_PublishLogRepository.GetList(new RB_Contribute_PublishLog_ViewModel() { Group_Id = userInfo.Group_Id, ContributeId = contributeId });
            return list;
        }

        #endregion

    }
}
