package cygx

import (
	"errors"
	"fmt"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

func AppendItemsLog(items []*cygx.CygxResearchSummaryLog, item []*cygx.CygxRSlChartPermission, logType, sort string) (itemsResult []*cygx.CygxResearchSummaryLog, msg string, err error) {
	mapSort := make(map[string]int)
	for _, v := range item {
		for _, v2 := range v.List {
			item := new(cygx.CygxResearchSummaryLog)
			if mapSort[v.ChartPermissionSort] != 0 && mapSort[v.ChartPermissionSort] != v.ChartPermissionId {
				msg = "有内容行业分类，序号不能为空"
				return
			}
			mapSort[v.ChartPermissionSort] = v.ChartPermissionId
			item.Type = logType
			item.Sort = strings.ToUpper(sort)
			item.ChartPermissionId = v.ChartPermissionId
			item.ChartPermissionSort = v.ChartPermissionSort
			item.CreateTime = time.Now()
			item.Body = GetRichtext(v2.Body)
			item.ReportLink = v2.ReportLink
			if item.ReportLink != "" {
				articleIdLink, errArt := GetReportLinkToArticleid(item.ReportLink)
				if errArt != nil && errArt.Error() != utils.ErrNoRow() {
					msg = "获取信息失败"
					err = errArt
					return
				}
				item.LinkArticleId = articleIdLink
			}
			items = append(items, item)
		}
	}
	itemsResult = items
	return
}

func AppendMinutesItemsLog(items []*cygx.CygxMinutesSummaryLog, item []*cygx.CygxRSlChartPermission, logType, sort string) (itemsResult []*cygx.CygxMinutesSummaryLog, msg string, err error) {
	mapSort := make(map[string]int)
	for _, v := range item {
		for _, v2 := range v.List {
			item := new(cygx.CygxMinutesSummaryLog)
			if mapSort[v.ChartPermissionSort] != 0 && mapSort[v.ChartPermissionSort] != v.ChartPermissionId {
				msg = "有内容行业分类，序号不能为空"
				return
			}
			mapSort[v.ChartPermissionSort] = v.ChartPermissionId
			item.Type = logType
			item.Sort = strings.ToUpper(sort)
			item.ChartPermissionId = v.ChartPermissionId
			item.ChartPermissionSort = v.ChartPermissionSort
			item.CreateTime = time.Now()
			item.Body = GetRichtext(v2.Body)
			item.ReportLink = v2.ReportLink
			if item.ReportLink != "" {
				articleIdLink, errArt := GetReportLinkToArticleid(item.ReportLink)
				if errArt != nil && errArt.Error() != utils.ErrNoRow() {
					msg = "获取信息失败"
					err = errArt
					return
				}
				item.LinkArticleId = articleIdLink
			}
			items = append(items, item)
		}
	}
	itemsResult = items
	return
}

// 通过接解析获取文章ID
func GetReportLinkToArticleid(reportLink string) (articleId int, err error) {
	var artMd5 string
	//处理报告的
	strnum1 := strings.Index(reportLink, "id=")
	if strnum1 > 0 {
		sliceId := strings.Split(reportLink, "id=")
		if len(sliceId) > 1 {
			reportLink = sliceId[1]
			sliceMd5Id := strings.Split(reportLink, "&")
			artMd5 = sliceMd5Id[0]
		}
		if artMd5 != "" {
			detail, errArt := cygx.GetArticleDetailByMd5Id(artMd5)
			if errArt != nil && errArt.Error() != utils.ErrNoRow() {
				err = errArt
				return
			}
			if detail != nil {
				articleId = detail.ArticleId
			}
		}
	} else {
		//处理活动的
		linkList := strings.Split(reportLink, "/")
		if linkList[len(linkList)-1] != "" {
			linkArticleId, _ := strconv.Atoi(linkList[len(linkList)-1])
			if linkArticleId > 0 {
				articleInfo, errArt := cygx.GetArticleIdInfoByArticleId(linkArticleId)
				if errArt != nil && errArt.Error() != utils.ErrNoRow() {
					err = errArt
					return
				}
				if articleInfo != nil {
					articleId = articleInfo.ArticleId
				}
			}
		}
	}
	return
}

//
//func init() {
//	DoArticleOnenIdWxTemplateMsg(1000614, 1)
//}

// 过滤策略平台报告，研选报告重复推送，以及权限勾选的推送
func DoArticleOnenIdWxTemplateMsg(articleId int, source int) (err error) {
	//优先排序： 预约纪要 > 关注作者 > 关注产业
	//source 来源 1研选  ，2 策略平台的报告
	//industrialSubjectIds 标的ID ，发布活动的时候使用

	var msg string
	var industrialSubjectIds string
	defer func() {
		//fmt.Println()
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.SendAlarmMsg("过滤策略平台报告，研选报告重复推送，以及权限勾选的推送，发送模版消息失败，Err："+err.Error()+";msg:"+msg, 3)
			utils.FileLog.Info(fmt.Sprintf("发送模版消息失败,Err:%s,%s", err.Error(), msg))
		}
		if msg != "" {
			utils.FileLog.Info("发送模版消息失败,msg:%s", msg)
		}
	}()
	articleInfo, err := cygx.GetArticleInfoOtherByArticleId(articleId)
	if err != nil {
		return
	}
	//对于已归类的报告，修改产业不做二次推送
	if articleInfo.IsClassFail == 0 && articleInfo.ArticleId < utils.SummaryArticleId {
		return err
	}
	articleInfo.Abstract, _ = utils.GetReportContentTextSub(articleInfo.Abstract)
	industrialSubjectIds, err = cygx.GetSubjectIds(articleId)
	if err != nil {
		return err
	}
	var chartPermissionId int
	if source == 1 {
		chartPermissionId = utils.CHART_PERMISSION_ID_YANXUAN
	} else {
		var chartPermissionName string
		reportMapDetail, err := cygx.GetCygxReportMappingRespByid(articleInfo.CategoryId)
		if err != nil {
			return err
		}
		//处理策略与非策略 的权限判断
		if reportMapDetail.ChartPermissionName == utils.CE_LUE_NAME {
			chartPermissionId = utils.CE_LUE_ID
		} else {
			if reportMapDetail.PermissionType == 1 {
				chartPermissionName = reportMapDetail.ChartPermissionName + "(主观)"
			} else {
				chartPermissionName = reportMapDetail.ChartPermissionName + "(客观)"
			}
			chartPermissionDetail, err := models.GetChartPermissionByRemark(chartPermissionName)
			if err != nil {
				return err
			}
			chartPermissionId = chartPermissionDetail.ChartPermissionId
		}
	}
	//文章关联的产业
	var industryName string
	var industrialManagementId string
	detailIndustryNameList, err := cygx.GetIndustrialManagemenDetailByAaticleID(articleId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	for _, v := range detailIndustryNameList {
		industryName += v.IndustryName + ","
		industrialManagementId += strconv.Itoa(v.IndustrialManagementId) + ","
	}
	industryName = strings.TrimRight(industryName, ",")
	industrialManagementId = strings.TrimRight(industrialManagementId, ",")

	charInfo, err := cygx.GetCategoryInfoById(chartPermissionId)
	if err != nil {
		return err
	}

	//处理勾选了全部行业赛道的用户
	var allIn string
	allIn = DoXzsChooseSend(charInfo.PermissionName)
	if allIn != "" {
		allInList, err := cygx.GetCygxXzsChooseSendByAllIn(allIn)
		if err != nil && err.Error() != utils.ErrNoRow() {
			return err
		}
		if len(allInList) > 0 {
			var allInUserId string
			for _, v := range allInList {
				allInUserId += strconv.Itoa(v.UserId) + ","
			}
			allInUserId = strings.TrimRight(allInUserId, ",")

			userFllowIndustrialList, err := cygx.GetUserFllowIndustrialListByUserIdAndIndustrial(allInUserId, industrialManagementId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				return err
			}
			mapUserFllowed := make(map[string]int)
			for _, v := range userFllowIndustrialList {
				//用户ID与其关注的产业组成唯一索引，判断是否存在，如果不存在就进行自动关注
				mapUserFllowed[fmt.Sprint("uid:", v.UserId, "_Industrial:", v.IndustrialManagementId)] = v.UserId
			}
			//获取这些allIN用户的的信息进行遍历生成需要插入的数据
			userList, err := models.GetWxUserListByUserIdsHaveCompany(allInUserId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				return err
			}
			var industryFllowItems []*cygx.CygxIndustryFllow
			for _, v := range detailIndustryNameList {
				for _, vUser := range userList {
					//如果用户这个用户没有关注这个产业就进行自动关注
					if mapUserFllowed[fmt.Sprint("uid:", vUser.UserId, "_Industrial:", v.IndustrialManagementId)] == 0 {
						item := new(cygx.CygxIndustryFllow)
						item.IndustrialManagementId = v.IndustrialManagementId
						item.UserId = vUser.UserId
						item.Email = vUser.Email
						item.Mobile = vUser.Mobile
						item.RealName = vUser.RealName
						item.CompanyId = vUser.CompanyId
						item.CompanyName = vUser.CompanyName
						item.Source = 3
						item.Type = 1
						item.CreateTime = time.Now()
						item.ModifyTime = time.Now()
						industryFllowItems = append(industryFllowItems, item)
					}
				}
			}
			err = cygx.AddCygxIndustryFllowMulti(industryFllowItems)
			if err != nil {
				go alarm_msg.SendAlarmMsg("用户关注全部赛道，出现新赛道批量添加失败 ，AddCygxIndustryFllowMulti ErrMsg:"+err.Error(), 2)
			}
		}
	}
	//处理勾选了全部行业赛道的用户之后，再判断是否推送过
	cacheKey := fmt.Sprint("Source:ADMIN", "_ArticleId:", articleId)
	isExist := utils.Rc.IsExist(cacheKey)
	if isExist {
		return err
	}
	setNX := utils.Rc.SetNX(cacheKey, articleId, time.Minute*30)
	if !setNX {
		go alarm_msg.SendAlarmMsg("发送模版消息失败，设置Redis Key 过期时间失败：key"+cacheKey, 3)
		return err
	}

	//cacheKey := fmt.Sprint("Source:ADMIN", "_ArticleId:", articleId)
	//ttlTime := utils.Rc.GetRedisTTL(cacheKey)
	//if ttlTime > 0 {
	//	return err
	//}
	//
	//utils.Rc.Put(cacheKey, articleId, time.Minute*30)
	// 获取所有有权的用户的 openid
	mapOpenidPower := make(map[int]string)
	openidPowerList, err := cygx.GetCygxUserRecordPower(strconv.Itoa(chartPermissionId))
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	for _, v := range openidPowerList {
		mapOpenidPower[v.UserId] = v.OpenId
	}

	//获取关注这个文章对应产业的用户的 openid
	mapOpenidFllow := make(map[int]string)
	openidFllowList, err := cygx.GetCygxUserFllowOpenid(articleId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	for _, v := range openidFllowList {
		mapOpenidFllow[v.UserId] = v.OpenId
	}

	//获取关注这个文章对应作者的用户的 openid
	mapOpenidDepartmentFllow := make(map[int]string)
	openidDepartmentFllowList, err := cygx.GetCygxUserFllowDepartmentOpenid(articleId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	for _, v := range openidDepartmentFllowList {
		mapOpenidDepartmentFllow[v.UserId] = v.OpenId
	}

	//获取拒绝接收推送的的用户的 openid
	mapOpenidRefuset := make(map[int]string)
	openidRefusetList, err := cygx.GetCygxUserRefusetOpenid()
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	for _, v := range openidRefusetList {
		mapOpenidRefuset[v.UserId] = v.OpenId
	}

	//获取提交过推送规则的用户的 openid
	mapUserIdChooseSend := make(map[int]int)
	chooseSendtList, err := cygx.GetCygxXzsChooseSend("")
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	for _, v := range chooseSendtList {
		mapUserIdChooseSend[v.UserId] = v.UserId
	}

	//已经推送了的openid
	mapOpenidPushed := make(map[int]string)

	keyword2 := articleInfo.Title
	keyword3 := articleInfo.PublishDate.Format(utils.FormatDate)
	if source == 2 {
		keyword3 = time.Now().Format(utils.FormatDate)
	}
	keyword4 := articleInfo.Abstract
	if source == 1 {
		if articleInfo.IsSummary == 1 {
			//优先推送1： 预约纪要
			if industrialSubjectIds != "" {
				mapActivityMobile := make(map[string]string)
				appointmentSummaryList, err := cygx.GetCygxAppointmentSummaryListBySubjectId(industrialSubjectIds)
				if err != nil && err.Error() != utils.ErrNoRow() {
					fmt.Println(err)
					return err
				}
				if len(appointmentSummaryList) > 0 {
					for _, v := range appointmentSummaryList {
						mapActivityMobile[fmt.Sprintf(v.Mobile)] += v.ActivityName + ","
					}
					if len(mapActivityMobile) > 0 {
						for k := range mapActivityMobile {
							openIditem, err := cygx.GetUserRecordOpenidByMobile(k)
							if err != nil && err.Error() != utils.ErrNoRow() {
								return err
							}
							//mfyxOpenIditem, err := cygx.GetMfyxUserRecordOpenidByMobile(k)
							if err != nil && err.Error() != utils.ErrNoRow() {
								return err
							}
							//如果没有权限或者没有获取到 openID的就不推送
							if openIditem == nil || mapOpenidPower[openIditem.UserId] == "" {
								continue
							}
							first := "您预约的调研，有关联的纪要发布/更新了"
							keyword1 := "您预约的调研，有关联的纪要发布/更新了"
							//keyword1 := strings.TrimRight(v, ",")
							//如果有权限而且小助手没有提交过信息的 就做正常推送
							if mapUserIdChooseSend[openIditem.UserId] == 0 {
								services.SendWxMsgWithCygxActivityAppointmentNew(first, keyword1, keyword2, keyword3, keyword4, openIditem, articleId)
								mapOpenidPushed[openIditem.UserId] = openIditem.OpenId
								// 研选发类目模板消息
								go services.SendWxCategoryMsgWithCygxActivityAppointmentNew("您预约的调研，有新报告发布", "已发布", utils.TruncateActivityNameString(articleInfo.Title), articleInfo.PublishDate.Format(utils.FormatDateTimeMinute2), openIditem, articleId)
							}

							//如果小助手勾选了对应的权限信息 就做正常推送
							if mapUserIdChooseSend[openIditem.UserId] != 0 && mapOpenidFllow[openIditem.UserId] != "" {
								services.SendWxMsgWithCygxActivityAppointmentNew(first, keyword1, keyword2, keyword3, keyword4, openIditem, articleId)
								mapOpenidPushed[openIditem.UserId] = openIditem.OpenId
								// 研选发类目模板消息
								go services.SendWxCategoryMsgWithCygxActivityAppointmentNew("您预约的调研，有新报告发布", "已发布", utils.TruncateActivityNameString(articleInfo.Title), articleInfo.PublishDate.Format(utils.FormatDateTimeMinute2), openIditem, articleId)
							}
						}
					}
				}
			}
		}

		fmt.Println(openidDepartmentFllowList)
		//优先推送2： 关注作者
		for _, v := range openidDepartmentFllowList {
			//如果是已经推送的就不做推送
			if mapOpenidPushed[v.UserId] != "" {
				continue
			}

			//如果没有权限 的就不推送
			if mapOpenidPower[v.UserId] == "" {
				continue
			}
			openIditem := new(cygx.OpenIdList)
			openIditem.UserId = v.UserId
			openIditem.OpenId = v.OpenId
			first := "您关注的作者发布了新的报告"
			keyword1 := "作者【" + articleInfo.NickName + "】发布了新的报告"
			//如果有权限而且小助手没有提交过信息的 就做正常推送
			if mapUserIdChooseSend[openIditem.UserId] == 0 {
				services.SendWxMsgWithCygxActivityAppointmentNew(first, keyword1, keyword2, keyword3, keyword4, openIditem, articleId)
				mapOpenidPushed[openIditem.UserId] = openIditem.OpenId
				// 研选发类目模板消息
				go services.SendWxCategoryMsgWithCygxActivityAppointmentNew(articleInfo.NickName, "发布了新报告", utils.TruncateActivityNameString(articleInfo.Title), articleInfo.PublishDate.Format(utils.FormatDateTimeMinute2), openIditem, articleId)
			}
			//如果小助手勾选了对应的权限信息 就做正常推送
			if mapUserIdChooseSend[openIditem.UserId] != 0 && mapOpenidDepartmentFllow[openIditem.UserId] != "" {
				services.SendWxMsgWithCygxActivityAppointmentNew(first, keyword1, keyword2, keyword3, keyword4, openIditem, articleId)
				mapOpenidPushed[openIditem.UserId] = openIditem.OpenId
				// 研选发类目模板消息
				go services.SendWxCategoryMsgWithCygxActivityAppointmentNew(articleInfo.NickName, "发布了新报告", utils.TruncateActivityNameString(articleInfo.Title), articleInfo.PublishDate.Format(utils.FormatDateTimeMinute2), openIditem, articleId)
			}
		}
		//优先推送3： 关注产业
		for _, v := range openidFllowList {
			//如果是已经推送的就不做推送
			if mapOpenidPushed[v.UserId] != "" {
				continue
			}
			//如果没有权限 的就不推送
			if mapOpenidPower[v.UserId] == "" {
				continue
			}
			openIditem := new(cygx.OpenIdList)
			openIditem.UserId = v.UserId
			openIditem.OpenId = v.OpenId
			//first := "您关注的产业有更新报告"
			//keyword1 := industryName
			first := "您关注的赛道，有新的报告发布/更新，欢迎查看"
			keyword1 := "【" + industryName + "】有报告发布/更新"
			//如果有权限而且小助手没有提交过信息的 就做正常推送
			if mapUserIdChooseSend[openIditem.UserId] == 0 {
				services.SendWxMsgWithCygxActivityAppointmentNew(first, keyword1, keyword2, keyword3, keyword4, openIditem, articleId)
				mapOpenidPushed[openIditem.UserId] = openIditem.OpenId
				// 研选发类目模板消息
				go services.SendWxCategoryMsgWithCygxActivityAppointmentNew(industryName, "发布了新报告", utils.TruncateActivityNameString(articleInfo.Title), articleInfo.PublishDate.Format(utils.FormatDateTimeMinute2), openIditem, articleId)
			}
			//如果小助手勾选了对应的权限信息 就做正常推送
			if mapUserIdChooseSend[openIditem.UserId] != 0 && mapOpenidFllow[openIditem.UserId] != "" {
				services.SendWxMsgWithCygxActivityAppointmentNew(first, keyword1, keyword2, keyword3, keyword4, openIditem, articleId)
				mapOpenidPushed[openIditem.UserId] = openIditem.OpenId
				// 研选发类目模板消息
				go services.SendWxCategoryMsgWithCygxActivityAppointmentNew(industryName, "发布了新报告", utils.TruncateActivityNameString(articleInfo.Title), articleInfo.PublishDate.Format(utils.FormatDateTimeMinute2), openIditem, articleId)
			}
		}
		//针对哪些没有关注作者，没有关注产业，没有预约纪要的人的推送
		for k, v := range mapOpenidPower {
			//如果是已经推送的就不做推送
			if mapOpenidPushed[k] != "" {
				continue
			}
			openIditem := new(cygx.OpenIdList)
			openIditem.UserId = k
			openIditem.OpenId = v
			first := "您关注的赛道，有新的报告发布/更新，欢迎查看"
			keyword1 := "【" + industryName + "】有报告发布/更新"

			//如果有权限而且小助手没有提交过信息的 就做正常推送
			if mapUserIdChooseSend[openIditem.UserId] == 0 {
				services.SendWxMsgWithCygxActivityAppointmentNew(first, keyword1, keyword2, keyword3, keyword4, openIditem, articleId)
				// 研选发类目模板消息
				go services.SendWxCategoryMsgWithCygxActivityAppointmentNew(industryName, "发布了新报告", utils.TruncateActivityNameString(articleInfo.Title), articleInfo.PublishDate.Format(utils.FormatDateTimeMinute2), openIditem, articleId)
			}
			//如果小助手勾选了对应的权限信息 就做正常推送
			if mapUserIdChooseSend[openIditem.UserId] != 0 && mapOpenidFllow[openIditem.UserId] != "" {
				services.SendWxMsgWithCygxActivityAppointmentNew(first, keyword1, keyword2, keyword3, keyword4, openIditem, articleId)
				// 研选发类目模板消息
				go services.SendWxCategoryMsgWithCygxActivityAppointmentNew(industryName, "发布了新报告", utils.TruncateActivityNameString(articleInfo.Title), articleInfo.PublishDate.Format(utils.FormatDateTimeMinute2), openIditem, articleId)
			}
		}

	} else {
		reportMapDetail, err := cygx.GetCygxReportMappingRespByid(articleInfo.CategoryId)
		if err != nil {
			return err
		}

		//如果是策略就按照策略的推送方式来写
		if reportMapDetail.ChartPermissionName == utils.CE_LUE_NAME {
			//获取提交过推送规则的用户的 openid
			mapUserFllowCeLue := make(map[int]string)
			userFllowCeLueList, err := cygx.GetCygxUserFllowCeLueOpenid(articleInfo.CategoryId)
			if err != nil {
				return err
			}
			for _, v := range userFllowCeLueList {
				mapUserFllowCeLue[v.UserId] = v.OpenId
			}
			industryName := reportMapDetail.SubCategoryName
			for k, v := range mapOpenidPower {
				if mapOpenidPushed[k] != "" {
					continue
				}
				openIditem := new(cygx.OpenIdList)
				openIditem.UserId = k
				openIditem.OpenId = v
				first := "您关注的赛道，有新的报告发布/更新，欢迎查看"
				keyword1 := "【" + industryName + "】有报告发布/更新"
				//如果有权限而且小助手没有提交过信息的 就做正常推送
				if mapUserIdChooseSend[openIditem.UserId] == 0 {
					services.SendWxMsgWithCygxActivityAppointmentNew(first, keyword1, keyword2, keyword3, keyword4, openIditem, articleId)
					// 研选发类目模板消息
					go services.SendWxCategoryMsgWithCygxActivityAppointmentNew(industryName, "发布了新报告", utils.TruncateActivityNameString(articleInfo.Title), articleInfo.PublishDate.Format(utils.FormatDateTimeMinute2), openIditem, articleId)
				}
				//如果小助手勾选了对应的权限信息 就做正常推送
				if mapUserIdChooseSend[openIditem.UserId] != 0 && mapUserFllowCeLue[openIditem.UserId] != "" {
					services.SendWxMsgWithCygxActivityAppointmentNew(first, keyword1, keyword2, keyword3, keyword4, openIditem, articleId)
					// 研选发类目模板消息
					go services.SendWxCategoryMsgWithCygxActivityAppointmentNew(industryName, "发布了新报告", utils.TruncateActivityNameString(articleInfo.Title), articleInfo.PublishDate.Format(utils.FormatDateTimeMinute2), openIditem, articleId)
				}
			}
		} else {
			for k, v := range mapOpenidPower {
				openIditem := new(cygx.OpenIdList)
				openIditem.UserId = k
				openIditem.OpenId = v
				first := "您关注的赛道，有新的报告发布/更新，欢迎查看"
				keyword1 := "【" + industryName + "】有报告发布/更新"
				//如果有权限而且小助手没有提交过信息的 就做正常推送
				if mapUserIdChooseSend[openIditem.UserId] == 0 {
					services.SendWxMsgWithCygxActivityAppointmentNew(first, keyword1, keyword2, keyword3, keyword4, openIditem, articleId)
					// 研选发类目模板消息
					go services.SendWxCategoryMsgWithCygxActivityAppointmentNew(industryName, "发布了新报告", utils.TruncateActivityNameString(articleInfo.Title), articleInfo.PublishDate.Format(utils.FormatDateTimeMinute2), openIditem, articleId)
				}
				//如果小助手勾选了对应的权限信息 就做正常推送
				if mapUserIdChooseSend[openIditem.UserId] != 0 && mapOpenidFllow[openIditem.UserId] != "" {
					services.SendWxMsgWithCygxActivityAppointmentNew(first, keyword1, keyword2, keyword3, keyword4, openIditem, articleId)
					// 研选发类目模板消息
					go services.SendWxCategoryMsgWithCygxActivityAppointmentNew(industryName, "发布了新报告", utils.TruncateActivityNameString(articleInfo.Title), articleInfo.PublishDate.Format(utils.FormatDateTimeMinute2), openIditem, articleId)
				}
			}
		}
	}
	go cygx.UpdateIsClassFail(articleInfo)
	return
}

//func init() {
//	DoThisWeekLastWeekWxTemplateMsg("标题", "20220909", "摘要", 2, 1)
//}

// 处理本周研究汇总，上周纪要汇总，报告精选
func DoThisWeekLastWeekWxTemplateMsg(title, publishDate, abstract string, articleId int, source int) (err error) {
	cacheKey := fmt.Sprint("Source:", source, "_ArticleId:", articleId)
	isExist := utils.Rc.IsExist(cacheKey)
	if isExist {
		return err
	}
	setNX := utils.Rc.SetNX(cacheKey, articleId, time.Minute*30)
	//如果key 设置成功就走推送
	if setNX {
		var msg string
		defer func() {
			//fmt.Println()
			if err != nil {
				fmt.Println("err：", err)
				go alarm_msg.SendAlarmMsg("过滤策略平台报告，研选报告重复推送，以及权限勾选的推送，发送模版消息失败，Err："+err.Error()+";msg:"+msg, 3)
				utils.FileLog.Info(fmt.Sprintf("发送模版消息失败,Err:%s,%s", err.Error(), msg))
			}
			if msg != "" {
				utils.FileLog.Info("发送模版消息失败,msg:%s", msg)
			}
		}()
		OpenIdList, err := models.GetCygxUserAllOpneid()
		if err != nil {
			return err
		}
		if len(OpenIdList) > 0 {
			var first, keyword1 string
			if source == 1 {
				keyword1 = "【报告精选】已发布"
			} else if source == 2 {
				keyword1 = "【本周研究汇总】已发布"
			} else {
				keyword1 = "【上周纪要汇总】已发布"
			}
			//keyword1 := "--"
			keyword2 := title
			keyword3 := strings.Replace(publishDate, "00:00:00", "", -1)
			keyword4 := abstract
			services.SendWxMsgThisWeekLastWeek(first, keyword1, keyword2, keyword3, keyword4, OpenIdList, articleId, source)
		}
	} else {
		go alarm_msg.SendAlarmMsg("发送模版消息失败，设置Redis Key 过期时间失败：key"+cacheKey, 3)
	}
	return
}

// 根据行业处理所选的全部赛道字段
func DoXzsChooseSend(chartPermissionName string) string {
	var allIn string
	if chartPermissionName == utils.YI_YAO_NAME {
		allIn = "all_in_yi_yao"
	} else if chartPermissionName == utils.XIAO_FEI_NAME {
		allIn = "all_in_xiao_fei"
	} else if chartPermissionName == utils.KE_JI_NAME {
		allIn = "all_in_ke_ji"
	} else if chartPermissionName == utils.ZHI_ZAO_NAME {
		allIn = "all_in_zhi_zao"
	} else if chartPermissionName == utils.CHART_PERMISSION_NAME_MF_YANXUAN {
		allIn = "all_in_yan_xuan"
	}
	return allIn
}

//func init() {
//	//MakeArticleMomentsImg(1000408)
//	var condition string
//	var pars []interface{}
//	condition = " AND   article_type_id  > 0   AND  publish_status   = 1   ORDER BY  article_id  DESC "
//	list, errList := cygx.GetCygxArticleList(condition, pars, 0, 999)
//	if errList != nil {
//		fmt.Println(errList)
//		return
//	}
//	fmt.Println("list", len(list))
//	//return
//	for k, v := range list {
//		fmt.Println(k)
//		MakeArticleMomentsImg(v.ArticleId)
//	}
//}

// 生成文章分享到朋友圈的图片
func MakeArticleMomentsImg(articleId int) {
	var err error
	//time.Sleep(3*time.Second) // 有时候同时添加多个活动，延迟三秒
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.SendAlarmMsg("生成文章分享到朋友圈的图片，MakeArticleMomentsImg Err："+err.Error()+"文章ID"+strconv.Itoa(articleId), 3)
		}
	}()
	articleInfo, e := cygx.GetArticleInfoOtherByArticleId(articleId)
	if e != nil {
		err = errors.New("GetArticleInfoOtherByArticleId, Err: " + e.Error())
		return
	}

	configCode := "article_moments_img_html"
	detailConfig, e := cygx.GetCygxConfigDetailByCode(configCode)
	if e != nil {
		err = errors.New("GetCygxConfigDetailByCode 获取生成文章分享到朋友圈的图片格式信息失败, Err: " + e.Error())
		return
	}
	configValue := detailConfig.ConfigValue
	configValue = strings.Replace(configValue, "{{Title}}", articleInfo.Title, -1)
	configValue = strings.Replace(configValue, "{{HeadImgUrl}}", articleInfo.HeadImgUrl, -1)
	configValue = strings.Replace(configValue, "{{NickName}}", articleInfo.NickName, -1)
	configValue = strings.Replace(configValue, "{{PublishDate}}", articleInfo.PublishDate.Format(utils.FormatDateTime), -1)
	configValue = strings.Replace(configValue, "{{Abstract}}", articleInfo.Abstract, -1)
	configValue = strings.Replace(configValue, "{{BodyText}}", articleInfo.BodyText, -1)

	htm2ImgReq := make(map[string]interface{})
	htm2ImgReq["html_content"] = configValue
	htm2ImgReq["width"] = 2250
	htm2ImgReq["height"] = 3813
	res, err := postHtml2Img(htm2ImgReq)
	if err != nil || res == nil {
		err = errors.New("html转图片失败: " + res.Msg)
		return
	}
	if res.Code != 200 {
		err = errors.New("html转图片失败: " + res.Msg)
		return
	}
	imgUrl := res.Data
	//fmt.Println(imgUrl)
	// 记录海报信息
	err = cygx.UpdateCygxArticleMomentsImg(imgUrl, articleId)
	return

}
