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
	} else if SourcePlatform == "1" {
		sourcePlatformResp = 1
	} else if SourcePlatform == "2" {
		sourcePlatformResp = 2
	} else {
		sourcePlatformResp, _ = strconv.Atoi(SourcePlatform)
	}
	return
}

// 处理文章来源类型
func GetArticleSourcePlatformText(sourcePlatformResp int) (sourcePlatformText string) {
	switch sourcePlatformResp {
	case 1:
		sourcePlatformText = "查研小程序"
	case 2:
		sourcePlatformText = "查研网页版"
	case 3:
		sourcePlatformText = "策略平台"
	case 5:
		sourcePlatformText = "研选小程序"
	case 6:
		sourcePlatformText = "研选网页版"
	default:
		sourcePlatformText = "查研小程序"
	}
	return
}

//func init() {
//	GetArticleSubjectLabelByArticleId([]int{9551, 9082})
//}

// 根据文章ID获取文章关联的产业名称
func GetArticleIndustrialLabelByArticleId(articleIds []int) (respMap map[int][]string) {
	if len(articleIds) == 0 {
		return
	}
	var err error
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg(fmt.Sprint("根据文章ID获取文章关联的产业名称失败 GetArticleIndustrialLabelByArticleId rticleIds: ", articleIds, err.Error()), 2)
		}
	}()
	list, e := cygx.GetIndustrialArticleGroupListByarticleIdsArr(articleIds)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetIndustrialArticleGroupListByarticleIdsArr, Err: " + e.Error())
		return
	}
	respMap = make(map[int][]string, 0)
	for _, v := range list {
		respMap[v.ArticleId] = append(respMap[v.ArticleId], v.IndustryName)
	}
	return
}

// 根据文章ID获取文章关联的标的名称
func GetArticleSubjectLabelByArticleId(articleIds []int) (respMap map[int][]string) {
	if len(articleIds) == 0 {
		return
	}
	var err error
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg(fmt.Sprint("根据文章ID获取文章关联的产业名称 失败 GetArticleSubjectLabelByArticleId rticleIds: ", articleIds, err.Error()), 2)
		}
	}()

	list, e := cygx.GetSubjectArticleGroupListByarticleIdsArr(articleIds)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetIndustrialArticleGroupListByarticleIdsArr, Err: " + e.Error())
		return
	}
	respMap = make(map[int][]string, 0)
	for _, v := range list {
		respMap[v.ArticleId] = append(respMap[v.ArticleId], v.SubjectName)
	}
	return
}

// 根据作者ID获取关联的文章下面的产业名称
func GetArticleIndustrialLabelByDepartmentId(departmentIds []int) (respMap map[int][]string) {
	lenArr := len(departmentIds)
	if lenArr == 0 {
		return
	}
	var err error
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg(fmt.Sprint("根据文章ID获取文章关联的产业名称失败 GetArticleIndustrialLabelByDepartmentId departmentIds: ", departmentIds, err.Error()), 2)
		}
	}()
	var condition string
	var pars []interface{}
	condition = " AND department_id IN(" + utils.GetOrmInReplace(lenArr) + ")  ORDER BY publish_date DESC "
	pars = append(pars, departmentIds)
	//获取作者关联的文章
	listArticle, e := cygx.GetArticlList(condition, pars, 0, 9999)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetArticlList, Err: " + e.Error())
		return
	}
	var articleIds []int
	for _, v := range listArticle {
		articleIds = append(articleIds, v.ArticleId)
	}
	//获取文章关联的产业
	list, e := cygx.GetIndustrialArticleGroupListByarticleIdsArr(articleIds)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetIndustrialArticleGroupListByarticleIdsArr, Err: " + e.Error())
		return
	}
	respMap = make(map[int][]string, 0)

	artMap := make(map[int][]string)
	for _, v := range list {
		artMap[v.ArticleId] = append(respMap[v.ArticleId], v.IndustryName)
	}

	//建立作者与文章、产业的关系
	for _, v := range listArticle {
		if len(artMap[v.ArticleId]) == 0 {
			continue
		}
		respMap[v.DepartmentId] = append(respMap[v.DepartmentId], strings.Join(artMap[v.ArticleId], "/"))
	}
	return
}

// 处理文章、研选专栏的查询信息回显
func HandleArticleAndYanxuanRecordList(items []*cygx.CygxArticleAndYanxuanRecordResp) (itemsResp []*cygx.UserInteraction, err error) {
	itemsResp = make([]*cygx.UserInteraction, 0)
	if len(items) > 0 {

		var articleIds []int        // 文章ID
		var yanxuanSpecialIds []int // 研选专栏ID
		var sellerCompanyIds []int  // 公司ID
		for _, v := range items {
			if v.Source == utils.CYGX_OBJ_ARTICLE {
				articleIds = append(articleIds, v.SourceId)
			}
			if v.Source == utils.CYGX_OBJ_YANXUANSPECIAL {
				yanxuanSpecialIds = append(yanxuanSpecialIds, v.SourceId)
			}
			sellerCompanyIds = append(sellerCompanyIds, v.CompanyId)
		}

		sellNameMap := services.GetSellNameMapByCompanyIds(sellerCompanyIds)

		mapIndustrialLabel := GetArticleIndustrialLabelByArticleId(articleIds) // 关联产业
		mapSubjectLabel := GetArticleSubjectLabelByArticleId(articleIds)       // 关联标的
		var condition string
		var pars []interface{}

		//获取文章map
		mapArticle := make(map[int]*cygx.CygxReportArticle)
		lenarticleIds := len(articleIds)
		if lenarticleIds > 0 {
			condition = " AND art.article_id IN  (" + utils.GetOrmInReplace(lenarticleIds) + ")  GROUP  BY art.article_id "
			pars = append(pars, articleIds)
			list, e := cygx.GetReportArticleList(condition, pars, 0, lenarticleIds, 1)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = e
				return
			}

			if len(list) > 0 {
				for _, v := range list {
					mapArticle[v.ArticleId] = v
				}
			}
		}

		//获取研选专栏map
		mapYanxuanSpecial := make(map[int]*cygx.CygxYanxuanSpeciaResplItem)
		lenyanxuanSpecialIds := len(yanxuanSpecialIds)
		if lenyanxuanSpecialIds > 0 {
			pars = make([]interface{}, 0)
			condition = " AND a.id IN  (" + utils.GetOrmInReplace(lenyanxuanSpecialIds) + ")"
			pars = append(pars, yanxuanSpecialIds)
			list, e := cygx.GetYanxuanSpecialListByCondition(condition, pars, 0, lenyanxuanSpecialIds)
			if e != nil && e.Error() != utils.ErrNoRow() {
				err = e
				return
			}
			if len(list) > 0 {
				for _, v := range list {
					mapYanxuanSpecial[v.Id] = v
				}
			}
		}

		for _, v := range items {
			item := new(cygx.UserInteraction)
			if v.Source == utils.CYGX_OBJ_ARTICLE {
				item.IndustryName = strings.Join(mapIndustrialLabel[v.SourceId], ",")
				item.SubjectNameStr = strings.Join(mapSubjectLabel[v.SourceId], ",")
				if v.SourceId >= utils.SummaryArticleId {
					item.ArticleType = 1
				} else {
					item.ArticleType = 2
				}
				//如果对应的map不为空，就赋值
				if mapArticle[v.SourceId] != nil {
					item.Title = mapArticle[v.SourceId].Title
					item.PublishDate = mapArticle[v.SourceId].PublishDate
					item.PermissionName = mapArticle[v.SourceId].PermissionName
					item.ArticleIdMd5 = mapArticle[v.SourceId].ArticleIdMd5
				}
			}
			if v.Source == utils.CYGX_OBJ_YANXUANSPECIAL {
				item.PermissionName = utils.CHART_PERMISSION_NAME_MF_YANXUAN
				//如果对应的map不为空，就赋值
				if mapYanxuanSpecial[v.SourceId] != nil {
					item.Title = mapYanxuanSpecial[v.SourceId].Title
					item.PublishDate = mapYanxuanSpecial[v.SourceId].PublishTime
					item.SpecialType = mapYanxuanSpecial[v.SourceId].Type
				}
			}
			item.ArticleId = v.SourceId
			item.CreateTime = v.CreateTime
			item.UserId = v.UserId
			item.RealName = v.RealName
			item.Mobile = v.Mobile
			item.CompanyId = v.CompanyId
			item.CompanyName = v.CompanyName
			item.SellerName = sellNameMap[v.CompanyId]
			item.RegisterPlatform = v.RegisterPlatform
			item.RegisterPlatformText = GetArticleSourcePlatformText(v.RegisterPlatform)
			item.StopTime = strconv.Itoa(v.StopTime)
			itemsResp = append(itemsResp, item)
		}

	}
	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
}
