package cygx

import (
	"errors"
	"fmt"
	"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"
	"strconv"
	"strings"
)

// 获取产品内测的阅读数据
func GetCygxProductInteriorHistoryListMap(productInteriorIs []int) (mapPv, mapUv map[int]int) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg("获取产品内测的阅读数据，信息失败，Err："+err.Error(), 3)
		}
	}()
	lenproductInteriorIs := len(productInteriorIs)
	if lenproductInteriorIs == 0 {
		return
	}
	var condition string
	var pars []interface{}
	condition = ` AND product_interior_id IN (` + utils.GetOrmInReplace(lenproductInteriorIs) + `)`
	pars = append(pars, productInteriorIs)
	list, err := cygx.GetCygxProductInteriorHistoryList(condition, pars)
	if err != nil {
		return
	}
	mapPv = make(map[int]int, 0)
	mapUv = make(map[int]int, 0)
	mapUvCount := make(map[string]int, 0)
	for _, v := range list {
		mapPv[v.ProductInteriorId]++
		if _, ok := mapUvCount[fmt.Sprint("UID_", v.UserId, "ProductInteriorId_", v.ProductInteriorId)]; !ok {
			mapUvCount[fmt.Sprint("UID_", v.UserId, "ProductInteriorId_", v.ProductInteriorId)] = v.ProductInteriorId
			mapUv[v.ProductInteriorId]++
		}
	}
	return
}

// 获取产品内测的留言数据
func GetCygxProductInteriorMsgListMap(productInteriorIs []int) (mapResp map[int]int) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg("获取产品内测的阅读数据，信息失败，Err："+err.Error(), 3)
		}
	}()
	lenproductInteriorIs := len(productInteriorIs)
	if lenproductInteriorIs == 0 {
		return
	}
	var condition string
	var pars []interface{}
	condition = ` AND product_interior_id IN (` + utils.GetOrmInReplace(lenproductInteriorIs) + `)`
	pars = append(pars, productInteriorIs)
	list, err := cygx.GetCygxProductInteriorMsgList(condition, pars)
	if err != nil {
		return
	}
	mapResp = make(map[int]int, 0)
	for _, v := range list {
		mapResp[v.ProductInteriorId]++
	}
	return
}

// 获取产品内测的标签数据
func GetCygxProductInteriorLabelListMap(productInteriorIs []int) (mapResp map[int]string) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg("获取产品内测的阅读数据，信息失败，Err："+err.Error(), 3)
		}
	}()
	lenproductInteriorIs := len(productInteriorIs)
	if lenproductInteriorIs == 0 {
		return
	}
	var condition string
	var pars []interface{}
	condition = ` AND product_interior_id IN (` + utils.GetOrmInReplace(lenproductInteriorIs) + `)`
	pars = append(pars, productInteriorIs)
	industrialList, err := cygx.GetProductInteriorIndustrialGroupManagement(condition, pars)
	if err != nil {
		return
	}

	subjectList, err := cygx.GetProductInteriorIndustrialGroupSubjectt(condition, pars)
	if err != nil {
		return
	}

	mapIndustrial := make(map[int]string)
	mapSubject := make(map[string]string)

	//合并活动对应的多个标的
	for _, v := range subjectList {
		mapSubject[fmt.Sprint(v.ProductInteriorId, "_", v.IndustrialManagementId)] += v.SubjectName + "/"
	}
	//活动对应的产业
	for _, v := range industrialList {
		var labelSubject string
		labelSubject = mapSubject[fmt.Sprint(v.ProductInteriorId, "_", v.IndustrialManagementId)]
		if labelSubject != "" {
			mapIndustrial[v.ProductInteriorId] += v.IndustryName + "--" + strings.TrimRight(labelSubject, "/") + "，"
		} else {
			mapIndustrial[v.ProductInteriorId] += v.IndustryName + "，"
		}
	}
	for _, v := range industrialList {
		mapIndustrial[v.ProductInteriorId] = strings.TrimRight(mapIndustrial[v.ProductInteriorId], "，")
	}
	mapResp = mapIndustrial
	return
}

//func init() {
//	SendWxMsgWithCygxProductInterior(20)
//}

// 模版消息推送
func SendWxMsgWithCygxProductInterior(productInteriorId int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.SendAlarmMsg("查研观向处理活动是否进行模板消息推送，发送模版消息失败，Err："+err.Error(), 3)
			utils.FileLog.Info(fmt.Sprintf("发送模版消息失败,Err:%s,%s", err.Error()))
		}
	}()
	detail, e := cygx.GetCygxProductInteriorDetail(productInteriorId)
	if e != nil {
		err = errors.New("获取详情失败" + e.Error())
		return
	}
	if detail == nil {
		err = errors.New("获取详情失败")
		return
	}
	if detail.IsSendWxMsg == 1 {
		return
	}
	//if detail.MatchTypeId > 0 {
	//	matchDetail, e := cygx.GetCygxReportMappingCygxDetail(detail.MatchTypeId)
	//	if e != nil {
	//		err = errors.New("GetCygxReportMappingCygxDetail" + e.Error())
	//		return
	//	}
	//	if matchDetail != nil {
	//		detail.MatchTypeName = matchDetail.MatchTypeName
	//	}
	//}
	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
	}
	var industrialName string
	industrialName = detail.ColumnName //用栏目名称
	//industrialList, e := cygx.GetProductInteriorIndustrialGroupManagementList(productInteriorId)
	//if e != nil && e.Error() != utils.ErrNoRow() {
	//	err = errors.New("GetProductInteriorIndustrialGroupManagementList，Err:" + e.Error())
	//	return
	//}
	//
	////关联的产业推送产业，没有关联产业的推送行业 p2_867 2023-8-30
	//if len(industrialList) == 0 {
	//	industrialName = detail.ColumnName //用栏目名称
	//} else {
	//	//mapOpenidFllow := make(map[int]string)
	//	//
	//	for _, vindustr := range industrialList {
	//		//获取关注对应产业的用户信息
	//		//industryFllowList, e := cygx.GetCygxUserindustryFllowOpenid(vindustr.IndustrialManagementId)
	//		//if e != nil {
	//		//	err = errors.New("获取关注对应产业的用户信息失败 " + e.Error())
	//		//	return
	//		//}
	//		//for _, v := range industryFllowList {
	//		//	mapOpenidFllow[v.UserId] = v.OpenId
	//		//}
	//		industrialName += vindustr.IndustryName + ";"
	//	}
	//	industrialName = strings.TrimRight(industrialName, ";")
	//}

	////获取拒绝接收推送的的用户的 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
	}

	first := "您关注的赛道，有新的报告发布/更新，欢迎查看"
	keyword1 := "【" + industrialName + "】有报告发布/更新"
	keyword2 := detail.Title
	keyword3 := utils.TimeRemoveHms2(detail.PublishTime)
	keyword4 := detail.Abstract
	remark := "点击查看报告详情"
	var redirectUrl string
	redirectUrl = utils.WX_MSG_PATH_PRODUCTINTERIOR_DETAIL + strconv.Itoa(detail.ProductInteriorId) + "&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.TemplateIdByProductXzs
	sendInfo.RedirectUrl = redirectUrl
	sendInfo.RedirectTarget = 3
	sendInfo.Resource = strconv.Itoa(detail.ProductInteriorId)
	sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ROADSHOW_VIDEO
	sendInfo.OpenIdArr = openIdArr
	e = services.SendTemplateMsg(sendInfo)
	if e != nil {
		err = errors.New("推送模板消息失败" + e.Error())
		return
	}
	e = cygx.UpdateProductInteriorIsSendWxMsg(productInteriorId, 1)
	if e != nil {
		err = errors.New("修改推送状态失败" + e.Error())
		return
	}
	return
}
