package cygx

import (
	"errors"
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"html"
	"strconv"
	"strings"
)

func ArticlePublishDate(publishDate string) (newPublishDate string) {
	newPublishDate = strings.Replace(publishDate, "00:00:00", "", -1)
	newPublishDate = strings.Replace(newPublishDate, " ", "", -1)
	return
}

func GetReportContentTextSubNew(content string) (contentSub string, err error) {
	content = html.UnescapeString(content)
	doc, errdoc := goquery.NewDocumentFromReader(strings.NewReader(content))
	if errdoc != nil {
		err = errdoc
		return
	}
	docText := doc.Text()
	bodyRune := []rune(docText)
	bodyRuneLen := len(bodyRune)
	body := string(bodyRune[:bodyRuneLen])
	contentSub = body
	contentSub = strings.Replace(contentSub, "Powered by Froala Editor", "", -1)
	contentSub = strings.Replace(contentSub, " ", "", -1)
	contentSub = strings.Replace(contentSub, "<p data-f-id=\"pbf\" style=\"text-align: center; font-size: 14px; margin-top: 30px; opacity: 0.65; font-family: sanered by <a href=\"https://www.froala.com/wysiwyg-editor?pb=1\" title=\"Froala Editor\">Froala Editor</a></p>", "", -1)
	return
}

func ArticleComPanyLabelToStr(companyLabel []string) (label string) {
	for _, v := range companyLabel {
		label += v + "{|}"
	}
	label = strings.TrimRight(label, "{|}")
	return
}

// GetArticleStockMap 获取个股标签所对应的文章ID
func GetArticleStockMap() (mapResp map[string]int, err error) {
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("获取个股标签所对应的文章ID失败"+err.Error(), 2)
		}
	}()
	list, err := cygx.GetArticleStock()
	if err != nil && err.Error() != utils.ErrNoRow() {
		return
	}
	mapResp = make(map[string]int, 0)
	if len(list) > 0 {
		//一对一精准匹配
		for _, v := range list {
			sliceSubjects := strings.Split(v.Stock, "/")
			if len(sliceSubjects) > 0 {
				for _, vSubject := range sliceSubjects {
					sliceKuohao := strings.Split(vSubject, "(")           //过滤括号
					sliceXiahuaxian := strings.Split(sliceKuohao[0], "-") //过滤下划线
					subject := sliceXiahuaxian[0]
					mapResp[subject] = v.ArticleId
				}
			}
		}
	}
	return
}

// 处理文章来源类型
func GetArticleSourcePlatform(SourcePlatform string) (sourcePlatformResp int) {
	//SourcePlatform        string `description:"来源 'MOBILE：移动端小程序','PC：PC端小程序','CELUE：上海策略平台','WEB：查研观向网页版'"`
	if SourcePlatform == "MOBILE" || SourcePlatform == "PC" {
		sourcePlatformResp = 1
	} else if SourcePlatform == "WEB" {
		sourcePlatformResp = 2
	} else if SourcePlatform == "CELUE" {
		sourcePlatformResp = 3
	}
	return
}

//
//func init() {
//	SendWxMsgWithroadshowEssence(1000546)
//}

// 路演精华的文章做模板消息推送
func SendWxMsgWithroadshowEssence(articleId int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg("路演精华的文章做模板消息推送送，发送模版消息失败，Err："+err.Error(), 3)
			utils.FileLog.Info(fmt.Sprintf("路演精华的文章做模板消息推送失败,Err:%s,%s", err.Error()))
		}
	}()
	detail, e := cygx.GetArticleRoadshowEssenceDetail(articleId)
	if e != nil {
		err = errors.New("获取详情失败" + e.Error())
		return
	}
	if detail == nil {
		err = errors.New("获取详情失败")
		return
	}
	//fmt.Println(detail)
	permissionStr, e := company.GetPermissionIdById(strconv.Itoa(detail.ChartPermissionId))
	if e != nil {
		err = errors.New("获取主客观权限失败" + e.Error())
		return
	}
	// 获取所有有权的用户的 openid
	openidPowerList, e := cygx.GetCygxUserRecordPower(permissionStr)
	if e != nil {
		err = errors.New("获取所有有权的用户的 openid失败" + e.Error())
		return
	}

	//获取关注对应产业的用户信息
	industryFllowList, e := cygx.GetCygxUserFllowOpenid(articleId)
	if e != nil {
		err = errors.New("获取关注对应产业的用户信息失败 " + e.Error())
		return
	}
	mapOpenidFllow := make(map[int]string)
	for _, v := range industryFllowList {
		mapOpenidFllow[v.UserId] = v.OpenId
	}

	//获取拒绝接收推送的的用户的 openid
	mapOpenidRefuset := make(map[int]string)
	openidRefusetList, e := cygx.GetCygxUserRefusetOpenid()
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("获取拒绝接收推送的的用户的 openid 失败" + e.Error())
		return
	}
	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
	}

	openIdArr := make([]string, len(openidPowerList))
	for i, v := range openidPowerList {
		if _, ok := mapOpenidRefuset[v.UserId]; ok {
			continue //如果用户选择了拒绝推送消息，那么就不做模板消息推送
		}
		if _, ok := mapUserIdChooseSend[v.UserId]; ok {
			if _, ok := mapOpenidFllow[v.UserId]; !ok {
				continue //如果用户提交过关注信息，而且这个产业他没有关注，那么不做推送
			}
		}
		openIdArr[i] = v.OpenId
	}
	fmt.Println(openIdArr)
	first := "【路演精华】已发布，欢迎查看"
	keyword1 := detail.Title
	keyword2 := "已发布"
	keyword3 := detail.PublishDate
	keyword4 := detail.Abstract
	remark := "点击查看详情"
	redirectUrl := utils.WX_MSG_PATH_ROAD_ESSENCE + strconv.Itoa(detail.ArticleId) + "&IsSendWx=1"
	sendInfo := new(services.SendWxTemplate)
	sendInfo.First = first
	sendInfo.Keyword1 = keyword1
	sendInfo.Keyword2 = keyword2
	sendInfo.Keyword3 = keyword3
	sendInfo.Keyword4 = keyword4
	sendInfo.Remark = remark
	sendInfo.TemplateId = utils.WxMsgTemplateIdActivityChangeApplyXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(detail.ArticleId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ROADSHOW_VIDEO
	sendInfo.OpenIdArr = openIdArr
	e = services.SendTemplateMsg(sendInfo)
	if e != nil {
		err = errors.New("推送模板消息失败" + e.Error())
		return
	}
	return
}
