package services

import (
	"encoding/json"
	"errors"
	"fmt"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/models/roadshow"
	"hongze/hongze_cygx/utils"
	"strconv"
	"time"
)

// 添加用户搜索标签到Redis
func KeyWordsWxUserRaiLabelRedisAdd(sourceId, uid int, label string) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			msg := fmt.Sprint("sourceId:", sourceId, "userId:", uid)
			go utils.SendAlarmMsg("用户关注产业更新相关标签，写入Redis队列消息失败："+err.Error()+msg, 2)
		}
	}()
	log := &models.WxUserRaiLabelRedis{UserId: uid, SourceId: sourceId, SourceType: 1, Label: label, CreateTime: time.Now(), RegisterPlatform: utils.REGISTER_PLATFORM}
	if utils.Re == nil {
		err := utils.Rc.LPush(utils.WX_USER_RAI_LABEL_KEY, log)
		if err != nil {
			fmt.Println("WxUserRaiLabelRedis LPush Err:" + err.Error())
		}
	}
	return
}

// 添加用户阅读文章标签到Redis
func ArticleWxUserRaiLabelRedisAdd(sourceId, uid int, createTime time.Time) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			msg := fmt.Sprint("sourceId:", sourceId, "userId:", uid)
			go utils.SendAlarmMsg("用户关注产业更新相关标签，写入Redis队列消息失败："+err.Error()+msg, 2)
		}
	}()
	log := &models.WxUserRaiLabelRedis{UserId: uid, SourceId: sourceId, SourceType: 1, TableName: utils.CYGX_OBJ_ARTICLE, CreateTime: createTime, RegisterPlatform: utils.REGISTER_PLATFORM}
	if utils.Re == nil {
		err := utils.Rc.LPush(utils.WX_USER_RAI_LABEL_KEY, log)
		if err != nil {
			fmt.Println("WxUserRaiLabelRedis LPush Err:" + err.Error())
		}
	}
	return
}

// 添加用户阅读本周研究汇总，与重点公司标签到Redis
func ReportSelectionWxUserRaiLabelRedisAdd(sourceId, uid int, createTime time.Time, tableName, label string) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			msg := fmt.Sprint("sourceId:", sourceId, "userId:", uid)
			go utils.SendAlarmMsg("用户关注产业更新相关标签，写入Redis队列消息失败："+err.Error()+msg, 2)
		}
	}()
	log := &models.WxUserRaiLabelRedis{UserId: uid, SourceId: sourceId, SourceType: 1, TableName: tableName, Label: label, CreateTime: createTime, RegisterPlatform: utils.REGISTER_PLATFORM}
	if utils.Re == nil {
		err := utils.Rc.LPush(utils.WX_USER_RAI_LABEL_KEY, log)
		if err != nil {
			fmt.Println("ReportSelectionWxUserRaiLabelRedisAdd LPush Err:" + err.Error())
		}
	}
	return
}

// 添加用户参加活动标签到Redis
func ActivityWxUserRaiLabelRedisAdd(sourceId, uid int, createTime time.Time) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			msg := fmt.Sprint("sourceId:", sourceId, "userId:", uid)
			go utils.SendAlarmMsg("添加用户参加活动标签，写入Redis队列消息失败："+err.Error()+msg, 2)
		}
	}()
	log := &models.WxUserRaiLabelRedis{UserId: uid, SourceId: sourceId, SourceType: 2, CreateTime: createTime, RegisterPlatform: utils.REGISTER_PLATFORM}
	if utils.Re == nil {
		err := utils.Rc.LPush(utils.WX_USER_RAI_LABEL_KEY, log)
		if err != nil {
			fmt.Println("ActivityWxUserRaiLabelRedisAdd LPush Err:" + err.Error())
		}
	}
	return
}

// 添加用户播放活动音视频标签到Redis
func ActivityVivoWxUserRaiLabelRedisAdd(sourceId, uid int, createTime time.Time) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			msg := fmt.Sprint("sourceId:", sourceId, "userId:", uid)
			go utils.SendAlarmMsg("添加用户参加活动标签，写入Redis队列消息失败："+err.Error()+msg, 2)
		}
	}()
	log := &models.WxUserRaiLabelRedis{UserId: uid, SourceId: sourceId, SourceType: 9, CreateTime: createTime, RegisterPlatform: utils.REGISTER_PLATFORM}
	if utils.Re == nil {
		err := utils.Rc.LPush(utils.WX_USER_RAI_LABEL_KEY, log)
		if err != nil {
			fmt.Println("ActivityWxUserRaiLabelRedisAdd LPush Err:" + err.Error())
		}
	}
	return
}

// 添加用户阅读图表标签到Redis
func KeyChartWxUserRaiLabelRedisAdd(sourceId, uid int, label string) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			msg := fmt.Sprint("sourceId:", sourceId, "userId:", uid)
			go utils.SendAlarmMsg("用户关注产业更新相关标签，写入Redis队列消息失败："+err.Error()+msg, 2)
		}
	}()
	log := &models.WxUserRaiLabelRedis{UserId: uid, SourceId: sourceId, SourceType: 10, Label: label, CreateTime: time.Now(), RegisterPlatform: utils.REGISTER_PLATFORM}
	if utils.Re == nil {
		err := utils.Rc.LPush(utils.WX_USER_RAI_LABEL_KEY, log)
		if err != nil {
			fmt.Println("WxUserRaiLabelRedis LPush Err:" + err.Error())
		}
	}
	return
}

func UpdateWxUserRaiLabelRedis() (err error) {
	for {
		//	SourceType       int       `description:"来源1:搜索关键字标签、2:产业/个股标签(线下活动)、3:产业/个股标签(线下路演)、4:产业/个股标签(线上活动)、5:产业/个股标签(线上路演)、6:销售输入标签、7:产业/个股标签(报告)、8:报告类型标签"`
		utils.Rc.Brpop(utils.WX_USER_RAI_LABEL_KEY, func(b []byte) {
			var log models.WxUserRaiLabelRedis
			if err := json.Unmarshal(b, &log); err != nil {
				fmt.Println("json unmarshal wrong!")
				go utils.SendAlarmMsg("用户更新相关标签处理Redis队列消息失败："+err.Error()+string(b), 2)
			}
			go SendCygxTemplateRecordSource(log)
			if log.TableName == "" {
				switch log.SourceType {
				case 1:
					go KeyWordsWxUserRaiLabelRedisAddReduce(log)
					fmt.Println("搜索关键词")
					break
				case 2, 4:
					go ActivityWxUserRaiLabelRedisAddReduce(log)
					fmt.Println("活动到会")
					break
				case 3, 5:
					go RoadshowWxUserRaiLabelRedisAddReduce(log)
					fmt.Println("活动到会")
					break
				case 9:
					go ActivityVivoWxUserRaiLabelRedisAddReduce(log)
					fmt.Println("活动音视频播放")
					break
				default:
					fmt.Println(string(b))
					go utils.SendAlarmMsg("用户更新相关标签处理Redis队列消息失败："+string(b), 2)
				}
			} else {
				switch log.TableName {
				case utils.CYGX_OBJ_ARTICLE:
					go ArticleWxUserRaiLabelRedisAddReduce(log)
					fmt.Println("阅读文章")
				case "cygx_research_summary":
					go ReportSelectionWxUserRaiLabelRedisAddReduce(log)
					fmt.Println("阅读本周研究汇总")
				case "cygx_report_selection":
					go ReportSelectionWxUserRaiLabelRedisAddReduce(log)
					fmt.Println("阅读报告精选（重点公司）")

				}
			}

		})
	}
}

// 1:搜索关键词
func KeyWordsWxUserRaiLabelRedisAddReduce(log models.WxUserRaiLabelRedis) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("用户文章阅读更新相关标签，处理Redis队列消息失败："+err.Error()+fmt.Sprint("articleId", log.SourceId, "userId", log.UserId), 2)
		}
	}()
	userId := log.UserId
	label := log.Label
	if userId == 0 {
		return
	}
	wxUser, e := models.GetWxUserItemByUserId(userId)
	if e != nil {
		err = errors.New("GetWxUserItemByUserId" + e.Error())
		return
	}
	item := new(models.WxUserRaiLabel)
	item.UserId = wxUser.UserId
	item.RealName = wxUser.RealName
	item.Mobile = wxUser.Mobile
	item.Email = wxUser.Email
	item.CompanyId = wxUser.CompanyId
	item.CompanyName = wxUser.CompanyName
	item.Label = label
	item.SourceType = log.SourceType
	item.CreateTime = log.CreateTime
	item.ModifyTime = time.Now()
	item.RegisterPlatform = log.RegisterPlatform
	err = models.AddWxUserRaiLabel(item)
	if e != nil {
		err = errors.New("AddWxUserRaiLabel" + e.Error())
		return
	}
	return
}

//func init() {
//	log := models.WxUserRaiLabelRedis{UserId: 53840, SourceId: 1753, SourceType: 3, TableName: "", Label: "", CreateTime: time.Now(), RegisterPlatform: utils.REGISTER_PLATFORM}
//	RoadshowWxUserRaiLabelRedisAddReduce(log)
//}

// 2:产业/个股标签(线下活动)、 4:产业/个股标签(线上活动)
// 用户参加活动，相关标签
func ActivityWxUserRaiLabelRedisAddReduce(log models.WxUserRaiLabelRedis) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("用户参加活动，相关标签，处理Redis队列消息失败：ActivityWxUserRaiLabelRedisAddReduce"+err.Error()+fmt.Sprint("SourceId", log.SourceId, "userId", log.UserId), 2)
		}
	}()
	userId := log.UserId
	sourceId := log.SourceId
	wxUser, e := models.GetWxUserItemByUserId(userId)
	if e != nil {
		err = errors.New("GetWxUserItemByUserId" + e.Error())
		return
	}
	activityDetail, e := models.GetAddActivityDetailByActivityId(sourceId)
	if e != nil {
		err = errors.New("GetArticleDetailTestById" + e.Error())
		return
	}

	var sourceType int
	if activityDetail.ActivityType == 1 {
		sourceType = 4
	} else {
		sourceType = 2
	}

	//正常的有产业报告
	var labelArr []string
	//建立首页资源表，与产业的关系
	industrialList, e := models.GetIndustrialActivityGroupManagementListByActivityId(sourceId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetIndustrialArticleGroupManagementListByArticleId, Err: " + e.Error() + "sourceId：" + strconv.Itoa(sourceId))
		return
	}

	var items []*models.WxUserRaiLabel
	for _, v := range industrialList {
		item := new(models.WxUserRaiLabel)
		item.UserId = wxUser.UserId
		item.RealName = wxUser.RealName
		item.Mobile = wxUser.Mobile
		item.Email = wxUser.Email
		item.CompanyId = wxUser.CompanyId
		item.CompanyName = wxUser.CompanyName
		item.Label = v.IndustryName
		item.SourceType = sourceType
		item.SourceId = sourceId
		item.CreateTime = log.CreateTime
		item.ModifyTime = time.Now()
		item.RegisterPlatform = log.RegisterPlatform
		item.TableName = ""
		items = append(items, item)
		labelArr = append(labelArr, v.IndustryName)
	}

	//建立首页资源表，与标的 的关系
	subjectList, e := models.GetSubjectActivityGroupManagementListByActivityId(sourceId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetSubjectArticleGroupManagementListByArtcileId, Err: " + e.Error() + "sourceId：" + strconv.Itoa(sourceId))
		return
	}
	//fmt.Println("subjectList", subjectList)
	for _, v := range subjectList {
		item := new(models.WxUserRaiLabel)
		item.UserId = wxUser.UserId
		item.RealName = wxUser.RealName
		item.Mobile = wxUser.Mobile
		item.Email = wxUser.Email
		item.CompanyId = wxUser.CompanyId
		item.CompanyName = wxUser.CompanyName
		item.Label = v.SubjectName
		item.SourceType = sourceType
		item.SourceId = sourceId
		item.CreateTime = log.CreateTime
		item.ModifyTime = time.Now()
		item.RegisterPlatform = log.RegisterPlatform
		item.TableName = ""
		items = append(items, item)
		labelArr = append(labelArr, v.SubjectName)
	}

	//如果两个标签都没有，就添加临时标签
	if len(labelArr) == 0 {
		item := new(models.WxUserRaiLabel)
		item.UserId = wxUser.UserId
		item.RealName = wxUser.RealName
		item.Mobile = wxUser.Mobile
		item.Email = wxUser.Email
		item.CompanyId = wxUser.CompanyId
		item.CompanyName = wxUser.CompanyName
		item.Label = activityDetail.Label
		item.SourceType = sourceType
		item.SourceId = sourceId
		item.CreateTime = log.CreateTime
		item.ModifyTime = time.Now()
		item.RegisterPlatform = log.RegisterPlatform
		item.TableName = ""
		items = append(items, item)
		labelArr = append(labelArr, activityDetail.Label)
	}

	e = models.AddWxUserRaiLabelMulti(items, labelArr, userId)
	if e != nil {
		err = errors.New("AddWxUserRaiLabelMulti" + e.Error())
		return
	}

	return
}

// 3:产业/个股标签(路演线下活动)、 5:产业/个股标签(路演线上活动)
// 用户参加路演，相关标签
func RoadshowWxUserRaiLabelRedisAddReduce(log models.WxUserRaiLabelRedis) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("用户参加路演，相关标签，处理Redis队列消息失败：RoadshowWxUserRaiLabelRedisAddReduce"+err.Error()+fmt.Sprint("SourceId", log.SourceId, "userId", log.UserId), 2)
		}
	}()
	userId := log.UserId
	sourceId := log.SourceId
	wxUser, e := models.GetWxUserItemByUserId(userId)
	if e != nil {
		err = errors.New("GetWxUserItemByUserId" + e.Error())
		return
	}

	rsCalendar, e := roadshow.GetRsCalendarById(sourceId)
	if e != nil {
		err = errors.New("GetRsCalendarById" + e.Error())
		return
	}

	var sourceType int
	if rsCalendar.RoadshowType == "线下" {
		sourceType = 3
	} else {
		sourceType = 5
	}

	totalGroup, e := roadshow.GetRsCalendarMeetingLabelGroupByRsCalendarId(sourceId)
	if e != nil {
		err = errors.New("GetRsCalendarMeetingLabelGroupByRsCalendarId" + e.Error())
		return
	}
	//var lebelDetail []*cygx.RaiServeTagResp
	var label string
	var labelArr []string
	var items []*models.WxUserRaiLabel
	if totalGroup > 0 {
		listGroup, e := roadshow.GetRsCalendarMeetingLabelGroupListByRsCalendarId(sourceId)
		if e != nil {
			err = errors.New("GetRsCalendarMeetingLabelGroupByRsCalendarId" + e.Error())
			return
		}
		var industrialManagementIds []int
		var industrialSubjectIds []int

		mapindustrialManagementName := make(map[int]string)
		mapindustrialSubjectName := make(map[int]string)
		mapCelueName := make(map[int]string)
		for _, v := range listGroup {
			switch v.TagType {
			case 1:
				industrialManagementIds = append(industrialManagementIds, v.TagId)
			case 2:
				industrialSubjectIds = append(industrialSubjectIds, v.TagId)
			case 3:
				mapCelueName[v.TagId] = "策略"
			}
		}

		if len(industrialManagementIds) > 0 {
			IndustryList, e := models.GetIndustryListByConditionByIds(industrialManagementIds)
			if e != nil {
				err = errors.New("GetRsCalendarMeetingLabelGroupByRsCalendarId" + e.Error())
				return
			}
			for _, v := range IndustryList {
				mapindustrialManagementName[v.IndustrialManagementId] = v.IndustryName
			}
		}

		if len(industrialSubjectIds) > 0 {
			SubjectList, e := models.GetIndustrialSubjectDetailByIds(industrialSubjectIds)
			if e != nil {
				err = errors.New("GetIndustrialSubjectDetailByIds" + e.Error())
				return
			}
			for _, v := range SubjectList {
				mapindustrialSubjectName[v.IndustrialSubjectId] = v.SubjectName
			}
		}

		for _, v := range listGroup {
			switch v.TagType {
			case 1:
				label = mapindustrialManagementName[v.TagId]
			case 2:
				label = mapindustrialSubjectName[v.TagId]
			case 3:
				label = mapCelueName[v.TagId]
			}
			item := new(models.WxUserRaiLabel)
			item.UserId = wxUser.UserId
			item.RealName = wxUser.RealName
			item.Mobile = wxUser.Mobile
			item.Email = wxUser.Email
			item.CompanyId = wxUser.CompanyId
			item.CompanyName = wxUser.CompanyName
			item.Label = label
			item.SourceType = sourceType
			item.SourceId = sourceId
			item.CreateTime = log.CreateTime
			item.ModifyTime = time.Now()
			item.RegisterPlatform = log.RegisterPlatform
			item.TableName = ""
			items = append(items, item)
			labelArr = append(labelArr, label)
		}
	}

	e = models.AddWxUserRaiLabelMulti(items, labelArr, userId)
	if e != nil {
		err = errors.New("AddWxUserRaiLabelMulti" + e.Error())
		return
	}
	return
}

// 7:产业/个股标签(报告)、8:报告类型标签
func ArticleWxUserRaiLabelRedisAddReduce(log models.WxUserRaiLabelRedis) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("用户文章阅读更新相关标签，处理Redis队列消息失败："+err.Error()+fmt.Sprint("articleId", log.SourceId, "userId", log.UserId), 2)
		}
	}()
	userId := log.UserId
	sourceId := log.SourceId
	wxUser, e := models.GetWxUserItemByUserId(userId)
	if e != nil {
		err = errors.New("GetWxUserItemByUserId" + e.Error())
		return
	}
	//articleDetail, e := models.GetArticleDetailTestById(sourceId)
	//if e != nil {
	//	err = errors.New("GetArticleDetailTestById" + e.Error())
	//	return
	//}

	labelArr, sourceType := GetArticlelabelArrByArticleId(sourceId)
	if len(labelArr) == 0 {
		return
	}
	var items []*models.WxUserRaiLabel
	for _, v := range labelArr {
		item := new(models.WxUserRaiLabel)
		item.UserId = wxUser.UserId
		item.RealName = wxUser.RealName
		item.Mobile = wxUser.Mobile
		item.Email = wxUser.Email
		item.CompanyId = wxUser.CompanyId
		item.CompanyName = wxUser.CompanyName
		item.Label = v
		item.SourceType = sourceType
		item.SourceId = sourceId
		item.CreateTime = log.CreateTime
		item.ModifyTime = time.Now()
		item.RegisterPlatform = log.RegisterPlatform
		item.TableName = "cygx_article"
		items = append(items, item)
		//labelArr = append(labelArr, v.IndustryName)
	}

	//articlePermission, e := models.GetArticlePermission(articleDetail.CategoryId)
	//if e != nil {
	//	err = errors.New("GetArticlePermission" + e.Error())
	//	return
	//}
	//if articlePermission == nil {
	//	err = errors.New("报告权限不存在" + e.Error())
	//	return
	//}
	//articlePermissionName := articlePermission.PermissionName
	//matchTypeName := articlePermission.MatchTypeName
	//matchTypeNameArr := []string{"季度策略", "科技前沿（周报）", "本周荟", "智造精粹"}
	//
	////1；四大行业汇总类报告：季度策略、科技前沿（周报）、本周荟、智造精粹以报告类型做标签
	////2：策略、固收的所有报告，以报告类型做标签
	//if articlePermissionName == utils.CE_LUE_NAME || articlePermissionName == utils.GU_SHOU_NAME || utils.InArrayByStr(matchTypeNameArr, matchTypeName) { // 策略、固收的所有报告，以报告类型做标签
	//	if matchTypeName == "季度策略" {
	//		matchTypeName = articlePermissionName + matchTypeName //其中季度策略以：xx行业季度策略  呈现
	//	}
	//	item := new(models.WxUserRaiLabel)
	//	item.UserId = wxUser.UserId
	//	item.RealName = wxUser.RealName
	//	item.Mobile = wxUser.Mobile
	//	item.Email = wxUser.Email
	//	item.CompanyId = wxUser.CompanyId
	//	item.CompanyName = wxUser.CompanyName
	//	item.Label = matchTypeName
	//	item.SourceType = 8
	//	item.SourceId = sourceId
	//	item.CreateTime = log.CreateTime
	//	item.ModifyTime = time.Now()
	//	item.RegisterPlatform = log.RegisterPlatform
	//	item.TableName = "cygx_article"
	//	err = models.AddWxUserRaiLabel(item)
	//	if e != nil {
	//		err = errors.New("AddWxUserRaiLabel" + e.Error())
	//		return
	//	}
	//} else if articlePermissionName == utils.ZHOU_QI_NAME {
	//	//周期的行业深度、调研纪要、产业跟踪这些系列的报告用领域做标签，其余的周期报告，都用报告类型（也就是ficc定义的类型）做标签
	//	//其中周期的周度观点，以 周期周度观点 呈现
	//	matchTypeNameArrZhouqi := []string{"行业深度", "调研纪要", "产业跟踪"}
	//	if utils.InArrayByStr(matchTypeNameArrZhouqi, matchTypeName) {
	//		matchTypeName = articleDetail.FieldName
	//	}
	//	item := new(models.WxUserRaiLabel)
	//	item.UserId = wxUser.UserId
	//	item.RealName = wxUser.RealName
	//	item.Mobile = wxUser.Mobile
	//	item.Email = wxUser.Email
	//	item.CompanyId = wxUser.CompanyId
	//	item.CompanyName = wxUser.CompanyName
	//	item.Label = matchTypeName
	//	item.SourceType = 8
	//	item.SourceId = sourceId
	//	item.CreateTime = log.CreateTime
	//	item.ModifyTime = time.Now()
	//	item.RegisterPlatform = log.RegisterPlatform
	//	item.TableName = "cygx_article"
	//	e = models.AddWxUserRaiLabel(item)
	//	if e != nil {
	//		err = errors.New("AddWxUserRaiLabel" + e.Error())
	//		return
	//	}
	//} else {
	//	//正常的有产业报告
	//	var labelArr []string
	//	//建立首页资源表，与产业的关系
	//	industrialList, e := models.GetIndustrialArticleGroupManagementListByArticleId(sourceId)
	//	if e != nil && e.Error() != utils.ErrNoRow() {
	//		err = errors.New("GetIndustrialArticleGroupManagementListByArticleId, Err: " + e.Error() + "sourceId：" + strconv.Itoa(sourceId))
	//		return
	//	}
	//
	//	var items []*models.WxUserRaiLabel
	//	for _, v := range industrialList {
	//		item := new(models.WxUserRaiLabel)
	//		item.UserId = wxUser.UserId
	//		item.RealName = wxUser.RealName
	//		item.Mobile = wxUser.Mobile
	//		item.Email = wxUser.Email
	//		item.CompanyId = wxUser.CompanyId
	//		item.CompanyName = wxUser.CompanyName
	//		item.Label = v.IndustryName
	//		item.SourceType = 7
	//		item.SourceId = sourceId
	//		item.CreateTime = log.CreateTime
	//		item.ModifyTime = time.Now()
	//		item.RegisterPlatform = log.RegisterPlatform
	//		item.TableName = "cygx_article"
	//		items = append(items, item)
	//		labelArr = append(labelArr, v.IndustryName)
	//	}
	//
	//	//建立首页资源表，与标的 的关系
	//	subjectList, e := models.GetSubjectArticleGroupManagementListByArtcileId(sourceId)
	//	if e != nil && e.Error() != utils.ErrNoRow() {
	//		err = errors.New("GetSubjectArticleGroupManagementListByArtcileId, Err: " + e.Error() + "sourceId：" + strconv.Itoa(sourceId))
	//		return
	//	}
	//
	//	for _, v := range subjectList {
	//		item := new(models.WxUserRaiLabel)
	//		item.UserId = wxUser.UserId
	//		item.RealName = wxUser.RealName
	//		item.Mobile = wxUser.Mobile
	//		item.Email = wxUser.Email
	//		item.CompanyId = wxUser.CompanyId
	//		item.CompanyName = wxUser.CompanyName
	//		item.Label = v.SubjectName
	//		item.SourceType = 7
	//		item.SourceId = sourceId
	//		item.CreateTime = log.CreateTime
	//		item.ModifyTime = time.Now()
	//		item.RegisterPlatform = log.RegisterPlatform
	//		item.TableName = "cygx_article"
	//		items = append(items, item)
	//		labelArr = append(labelArr, v.SubjectName)
	//	}
	//	e = models.AddWxUserRaiLabelMulti(items, labelArr, userId)
	//	if e != nil {
	//		err = errors.New("AddWxUserRaiLabelMulti" + e.Error())
	//		return
	//	}
	//}

	e = models.AddWxUserRaiLabelMulti(items, labelArr, userId)
	if e != nil {
		err = errors.New("AddWxUserRaiLabelMulti" + e.Error())
		return
	}

	return
}

// 8:报告类型标签 (本周研究汇总，与重点公司)
func ReportSelectionWxUserRaiLabelRedisAddReduce(log models.WxUserRaiLabelRedis) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("报告类型标签 (本周研究汇总，与重点公司)，处理Redis队列消息失败：ReportSelectionWxUserRaiLabelRedisAddReduce"+err.Error()+fmt.Sprint("SourceId", log.SourceId, "userId", log.UserId), 2)
		}
	}()
	userId := log.UserId
	sourceId := log.SourceId
	wxUser, e := models.GetWxUserItemByUserId(userId)
	if e != nil {
		err = errors.New("GetWxUserItemByUserId" + e.Error())
		return
	}

	item := new(models.WxUserRaiLabel)
	item.UserId = wxUser.UserId
	item.RealName = wxUser.RealName
	item.Mobile = wxUser.Mobile
	item.Email = wxUser.Email
	item.CompanyId = wxUser.CompanyId
	item.CompanyName = wxUser.CompanyName
	item.Label = log.Label
	item.SourceType = 8
	item.SourceId = sourceId
	item.CreateTime = log.CreateTime
	item.ModifyTime = time.Now()
	item.RegisterPlatform = log.RegisterPlatform
	item.TableName = log.TableName
	err = models.AddWxUserRaiLabel(item)
	if e != nil {
		err = errors.New("AddWxUserRaiLabel" + e.Error())
		return
	}
	return
}

// 9:活动音视频回放标签处理
func ActivityVivoWxUserRaiLabelRedisAddReduce(log models.WxUserRaiLabelRedis) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("用户查看活动音视频回放，相关标签，处理Redis队列消息失败：ActivityVivoWxUserRaiLabelRedisAddReduce"+err.Error()+fmt.Sprint("SourceId", log.SourceId, "userId", log.UserId), 2)
		}
	}()
	userId := log.UserId
	sourceId := log.SourceId
	wxUser, e := models.GetWxUserItemByUserId(userId)
	if e != nil {
		err = errors.New("GetWxUserItemByUserId" + e.Error())
		return
	}
	activityDetail, e := models.GetAddActivityDetailByActivityId(sourceId)
	if e != nil {
		err = errors.New("GetAddActivityDetailByActivityId" + e.Error())
		return
	}

	var sourceType int
	sourceType = 9

	//正常的有产业报告
	var labelArr []string
	//建立首页资源表，与产业的关系
	industrialList, e := models.GetIndustrialActivityGroupManagementListByActivityId(sourceId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetIndustrialActivityGroupManagementListByActivityId, Err: " + e.Error() + "sourceId：" + strconv.Itoa(sourceId))
		return
	}

	var items []*models.WxUserRaiLabel
	for _, v := range industrialList {
		item := new(models.WxUserRaiLabel)
		item.UserId = wxUser.UserId
		item.RealName = wxUser.RealName
		item.Mobile = wxUser.Mobile
		item.Email = wxUser.Email
		item.CompanyId = wxUser.CompanyId
		item.CompanyName = wxUser.CompanyName
		item.Label = v.IndustryName
		item.SourceType = sourceType
		item.SourceId = sourceId
		item.CreateTime = log.CreateTime
		item.ModifyTime = time.Now()
		item.RegisterPlatform = log.RegisterPlatform
		item.TableName = ""
		items = append(items, item)
		labelArr = append(labelArr, v.IndustryName)
	}

	//建立首页资源表，与标的 的关系
	subjectList, e := models.GetSubjectActivityGroupManagementListByActivityId(sourceId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetSubjectActivityGroupManagementListByActivityId, Err: " + e.Error() + "sourceId：" + strconv.Itoa(sourceId))
		return
	}
	//fmt.Println("subjectList", subjectList)
	for _, v := range subjectList {
		item := new(models.WxUserRaiLabel)
		item.UserId = wxUser.UserId
		item.RealName = wxUser.RealName
		item.Mobile = wxUser.Mobile
		item.Email = wxUser.Email
		item.CompanyId = wxUser.CompanyId
		item.CompanyName = wxUser.CompanyName
		item.Label = v.SubjectName
		item.SourceType = sourceType
		item.SourceId = sourceId
		item.CreateTime = log.CreateTime
		item.ModifyTime = time.Now()
		item.RegisterPlatform = log.RegisterPlatform
		item.TableName = ""
		items = append(items, item)
		labelArr = append(labelArr, v.SubjectName)
	}

	//如果两个标签都没有，就添加临时标签
	if len(labelArr) == 0 {
		item := new(models.WxUserRaiLabel)
		item.UserId = wxUser.UserId
		item.RealName = wxUser.RealName
		item.Mobile = wxUser.Mobile
		item.Email = wxUser.Email
		item.CompanyId = wxUser.CompanyId
		item.CompanyName = wxUser.CompanyName
		item.Label = activityDetail.Label
		item.SourceType = sourceType
		item.SourceId = sourceId
		item.CreateTime = log.CreateTime
		item.ModifyTime = time.Now()
		item.RegisterPlatform = log.RegisterPlatform
		item.TableName = ""
		items = append(items, item)
		labelArr = append(labelArr, activityDetail.Label)
	}

	e = models.AddWxUserRaiLabelMulti(items, labelArr, userId)
	if e != nil {
		err = errors.New("AddWxUserRaiLabelMulti" + e.Error())
		return
	}

	return
}

//func init() {
//	fmt.Println(GetArticlelabelArrByArticleId(11796))
//}

func GetArticlelabelArrByArticleId(articleId int) (labelArr []string, sourceType int) {
	articleDetail, e := models.GetArticleDetailTestById(articleId)
	if e != nil {
		fmt.Println(e)
		return
	}
	if articleDetail.ArticleTypeId > 0 {
		//正常的有产业报告
		//建立首页资源表，与产业的关系
		industrialList, e := models.GetIndustrialArticleGroupManagementListByArticleId(articleId)
		if e != nil && e.Error() != utils.ErrNoRow() {
			fmt.Println(e)
			return
		}
		for _, v := range industrialList {
			labelArr = append(labelArr, v.IndustryName)
		}
		//建立首页资源表，与标的 的关系
		subjectList, e := models.GetSubjectArticleGroupManagementListByArtcileId(articleId)
		if e != nil && e.Error() != utils.ErrNoRow() {
			fmt.Println(e)
			return
		}
		for _, v := range subjectList {
			labelArr = append(labelArr, v.SubjectName)
		}
		sourceType = 7
		return
	}
	articlePermission, e := models.GetArticlePermission(articleDetail.CategoryId)
	if e != nil {
		fmt.Println(e)
		return
	}
	if articlePermission == nil {
		fmt.Println(e)
		return
	}
	articlePermissionName := articlePermission.PermissionName
	subCategoryName := articleDetail.SubCategoryName
	matchTypeNameArr := []string{"季度策略", "科技前言（周报）", "本周荟", "智造精粹"}
	//fmt.Println(subCategoryName)
	//1；四大行业汇总类报告：季度策略、科技前沿（周报）、本周荟、智造精粹以报告类型做标签
	//2：策略、固收的所有报告，以报告类型做标签
	//var labelArr []string
	if articlePermissionName == utils.CE_LUE_NAME || articlePermissionName == utils.GU_SHOU_NAME || utils.InArrayByStr(matchTypeNameArr, subCategoryName) { // 策略、固收的所有报告，以报告类型做标签
		if subCategoryName == "季度策略" {
			subCategoryName = articlePermissionName + subCategoryName //其中季度策略以：xx行业季度策略  呈现
		}
		labelArr = append(labelArr, subCategoryName)
		sourceType = 8
	} else if articlePermissionName == utils.ZHOU_QI_NAME {
		//周期的行业深度、调研纪要、产业跟踪这些系列的报告用领域做标签，其余的周期报告，都用报告类型（也就是ficc定义的类型）做标签
		//其中周期的周度观点，以 周期周度观点 呈现
		matchTypeNameArrZhouqi := []string{"行业深度", "调研纪要", "产业跟踪"}
		if utils.InArrayByStr(matchTypeNameArrZhouqi, subCategoryName) {
			subCategoryName = articleDetail.FieldName
		}
		labelArr = append(labelArr, subCategoryName)
		sourceType = 8
	} else {

		//正常的有产业报告
		//建立首页资源表，与产业的关系
		industrialList, e := models.GetIndustrialArticleGroupManagementListByArticleId(articleId)
		if e != nil && e.Error() != utils.ErrNoRow() {
			fmt.Println(e)
			return
		}
		for _, v := range industrialList {
			labelArr = append(labelArr, v.IndustryName)
		}
		//建立首页资源表，与标的 的关系
		subjectList, e := models.GetSubjectArticleGroupManagementListByArtcileId(articleId)
		if e != nil && e.Error() != utils.ErrNoRow() {
			fmt.Println(e)
			return
		}
		for _, v := range subjectList {
			labelArr = append(labelArr, v.SubjectName)
		}
		sourceType = 7
	}

	return
}

//func init() {
//	//fmt.Println(GetArticlelabelArrByArticleId(11037))
//	initCrm16_5ActivityVivo()
//}

func initCrm16_5keyWord() {

	listKeyWords, err := models.GetSearchKeyWordinitCrm16_5()

	if err != nil {
		fmt.Println(err)
		return
	}
	var mobiles []string
	mapMobile := make(map[string]bool)
	for _, v := range listKeyWords {
		if mapMobile[v.Mobile] || v.Mobile == "" {
			continue
		}
		mapMobile[v.Mobile] = true
		mobiles = append(mobiles, v.Mobile)
	}

	listUser, err := models.GetWxUserListByMobileArr(mobiles)

	if err != nil {
		fmt.Println(err)
		return
	}

	mapUser := make(map[string]*models.WxUserItem)

	for _, v := range listUser {
		mapUser[v.Mobile] = v
	}

	var items []*models.WxUserRaiLabelLog
	for _, v := range listKeyWords {
		if mapUser[v.Mobile] == nil || v.Mobile == "" {
			continue
		}

		wxUser := mapUser[v.Mobile]
		item := new(models.WxUserRaiLabelLog)
		item.UserId = wxUser.UserId
		item.RealName = wxUser.RealName
		item.Mobile = wxUser.Mobile
		item.Email = wxUser.Email
		item.CompanyId = wxUser.CompanyId
		item.CompanyName = wxUser.CompanyName
		item.Label = v.KeyWord
		item.SourceType = 1
		item.CreateTime = v.CreateTime
		item.ModifyTime = time.Now()
		item.RegisterPlatform = v.RegisterPlatform
		items = append(items, item)
	}
	fmt.Println(len(items))

	var itemsAdd []*models.WxUserRaiLabelLog
	if len(items) > 0 {
		for _, v := range items {
			itemsAdd = append(itemsAdd, v)
			if len(itemsAdd)%2000 == 0 {
				err = models.AddWxUserRaiLabelLogMultiInit(itemsAdd)
				if err != nil {
					fmt.Println(err)
					return
				}
				itemsAdd = make([]*models.WxUserRaiLabelLog, 0)
			}

		}
	}
	if len(itemsAdd) > 0 {
		err = models.AddWxUserRaiLabelLogMultiInit(itemsAdd)
		if err != nil {
			fmt.Println(err)
			return
		}
	}
	fmt.Println("endAddWxUserRaiLabelLogMultiInit")
}

func initCrm16_5Activity() {
	var condition string
	var pars []interface{}
	condition += ` AND	create_time > '2024-09-01'   AND  (is_meeting =1 OR duration != '')  `
	pars = append(pars)
	//获取提交到会的人员信息
	signUpDetailList, err := models.GetSignupDetailList(condition, pars)
	if err != nil {
		fmt.Println(err)
		return
	}
	var mobiles []string

	mapMobile := make(map[string]bool)

	for _, v := range signUpDetailList {
		if mapMobile[v.Mobile] || v.Mobile == "" {
			continue
		}
		mapMobile[v.Mobile] = true
		mobiles = append(mobiles, v.Mobile)
	}

	var activityIds []int
	mapactivityId := make(map[int]bool)
	for _, v := range signUpDetailList {
		if mapactivityId[v.ActivityId] {
			continue
		}
		mapactivityId[v.ActivityId] = true
		activityIds = append(activityIds, v.ActivityId)
	}

	listUser, err := models.GetWxUserListByMobileArr(mobiles)
	if err != nil {
		fmt.Println(err)
		return
	}
	mapUser := make(map[string]*models.WxUserItem)
	for _, v := range listUser {
		mapUser[v.Mobile] = v
	}

	activityDetailList, e := models.GetAddActivityDetailByActivityIdinitCrm16_5(activityIds)
	if e != nil {
		fmt.Println(e)
		return
	}

	sourceTypemap := make(map[int]int)
	mapLabel := make(map[int]string)

	for _, v := range activityDetailList {
		if v.ActivityType == 1 {
			sourceTypemap[v.ActivityId] = 4
		} else {
			sourceTypemap[v.ActivityId] = 2
		}
		mapLabel[v.ActivityId] = v.Label
	}

	//正常的有产业报告

	//建立首页资源表，与产业的关系
	industrialList, e := models.GetIndustrialActivityGroupManagementListByArticleIds(activityIds)
	if e != nil && e.Error() != utils.ErrNoRow() {
		fmt.Println(e)
		return
	}

	//建立首页资源表，与标的 的关系
	subjectList, e := models.GetSubjectActivityGroupManagementListByActivityIds(activityIds)
	if e != nil && e.Error() != utils.ErrNoRow() {
		fmt.Println(e)
		return
	}

	var items []*models.WxUserRaiLabelLog
	for _, v := range signUpDetailList {
		if mapUser[v.Mobile] == nil || v.Mobile == "" {
			continue
		}
		var haseName bool
		wxUser := mapUser[v.Mobile]
		for _, vI := range industrialList {
			if vI.ActivityId != v.ActivityId {
				continue
			}
			haseName = true
			item := new(models.WxUserRaiLabelLog)
			item.UserId = wxUser.UserId
			item.RealName = wxUser.RealName
			item.Mobile = wxUser.Mobile
			item.Email = wxUser.Email
			item.CompanyId = wxUser.CompanyId
			item.CompanyName = wxUser.CompanyName
			item.Label = vI.IndustryName
			item.SourceType = sourceTypemap[v.ActivityId]
			item.SourceId = v.ActivityId
			item.CreateTime = v.CreateTime
			item.ModifyTime = time.Now()
			item.TableName = ""
			//item.RegisterPlatform = v.RegisterPlatform
			items = append(items, item)
		}

		for _, vs := range subjectList {
			if vs.ActivityId != v.ActivityId {
				continue
			}
			haseName = true
			item := new(models.WxUserRaiLabelLog)
			item.UserId = wxUser.UserId
			item.RealName = wxUser.RealName
			item.Mobile = wxUser.Mobile
			item.Email = wxUser.Email
			item.CompanyId = wxUser.CompanyId
			item.CompanyName = wxUser.CompanyName
			item.Label = vs.SubjectName
			item.SourceType = sourceTypemap[v.ActivityId]
			item.SourceId = v.ActivityId
			item.CreateTime = v.CreateTime
			item.ModifyTime = time.Now()
			//item.RegisterPlatform = v.RegisterPlatform
			items = append(items, item)
		}

		//如果两个标签都没有，就添加临时标签
		if !haseName {
			item := new(models.WxUserRaiLabelLog)
			item.UserId = wxUser.UserId
			item.RealName = wxUser.RealName
			item.Mobile = wxUser.Mobile
			item.Email = wxUser.Email
			item.CompanyId = wxUser.CompanyId
			item.CompanyName = wxUser.CompanyName
			item.Label = mapLabel[v.ActivityId]
			item.SourceType = sourceTypemap[v.ActivityId]
			item.SourceId = v.ActivityId
			item.CreateTime = v.CreateTime
			item.ModifyTime = time.Now()
			//item.RegisterPlatform = v.RegisterPlatform
			item.TableName = ""
			items = append(items, item)
		}

	}
	//fmt.Println("initCrm16_5Activity", len(items))
	//return
	var itemsAdd []*models.WxUserRaiLabelLog
	if len(items) > 0 {
		for _, v := range items {
			itemsAdd = append(itemsAdd, v)
			if len(itemsAdd)%2000 == 0 {
				err = models.AddWxUserRaiLabelLogMultiInit(itemsAdd)
				if err != nil {
					return
				}
				itemsAdd = make([]*models.WxUserRaiLabelLog, 0)
			}

		}
	}
	if len(itemsAdd) > 0 {
		err = models.AddWxUserRaiLabelLogMultiInit(itemsAdd)
		if err != nil {
			return
		}
	}
	fmt.Println("endAddWxUserRaiLabelLogMultiInit")
}

func initCrm16_5ActivityVivo() {
	var condition string
	var pars []interface{}
	condition += ` AND	create_time > '2024-09-01'   `
	pars = append(pars)
	//获取提交到会的人员信息
	ActivityVoiceList, err := models.GetActivityVoiceHistoryByMobileListCRM_16_5Init(condition)
	if err != nil {
		fmt.Println(err)
		return
	}
	ActivityVideoList, err := models.GetActivityVideoHistoryByMobileListCRM_16_5Init(condition)
	if err != nil {
		fmt.Println(err)
		return
	}
	var mobiles []string

	mapMobile := make(map[string]bool)

	for _, v := range ActivityVoiceList {
		if mapMobile[v.Mobile] || v.Mobile == "" {
			continue
		}
		mapMobile[v.Mobile] = true
		mobiles = append(mobiles, v.Mobile)
	}

	for _, v := range ActivityVideoList {
		if mapMobile[v.Mobile] || v.Mobile == "" {
			continue
		}
		mapMobile[v.Mobile] = true
		mobiles = append(mobiles, v.Mobile)
	}

	var activityIds []int
	mapactivityId := make(map[int]bool)
	for _, v := range ActivityVoiceList {
		if mapactivityId[v.ActivityId] {
			continue
		}
		mapactivityId[v.ActivityId] = true
		activityIds = append(activityIds, v.ActivityId)
	}

	for _, v := range ActivityVideoList {
		if mapactivityId[v.ActivityId] {
			continue
		}
		mapactivityId[v.ActivityId] = true
		activityIds = append(activityIds, v.ActivityId)
	}

	listUser, err := models.GetWxUserListByMobileArr(mobiles)
	if err != nil {
		fmt.Println(err)
		return
	}
	mapUser := make(map[string]*models.WxUserItem)
	for _, v := range listUser {
		mapUser[v.Mobile] = v
	}

	activityDetailList, e := models.GetAddActivityDetailByActivityIdinitCrm16_5(activityIds)
	if e != nil {
		fmt.Println(e)
		return
	}

	//sourceTypemap := make(map[int]int)
	mapLabel := make(map[int]string)

	for _, v := range activityDetailList {
		//if v.ActivityType == 1 {
		//	sourceTypemap[v.ActivityId] = 4
		//} else {
		//	sourceTypemap[v.ActivityId] = 2
		//}
		mapLabel[v.ActivityId] = v.Label
	}

	//正常的有产业报告

	//建立首页资源表，与产业的关系
	industrialList, e := models.GetIndustrialActivityGroupManagementListByArticleIds(activityIds)
	if e != nil && e.Error() != utils.ErrNoRow() {
		fmt.Println(e)
		return
	}

	//建立首页资源表，与标的 的关系
	subjectList, e := models.GetSubjectActivityGroupManagementListByActivityIds(activityIds)
	if e != nil && e.Error() != utils.ErrNoRow() {
		fmt.Println(e)
		return
	}

	var items []*models.WxUserRaiLabelLog
	for _, v := range ActivityVoiceList {
		if mapUser[v.Mobile] == nil || v.Mobile == "" {
			continue
		}
		var haseName bool
		wxUser := mapUser[v.Mobile]
		for _, vI := range industrialList {
			if vI.ActivityId != v.ActivityId {
				continue
			}
			haseName = true
			item := new(models.WxUserRaiLabelLog)
			item.UserId = wxUser.UserId
			item.RealName = wxUser.RealName
			item.Mobile = wxUser.Mobile
			item.Email = wxUser.Email
			item.CompanyId = wxUser.CompanyId
			item.CompanyName = wxUser.CompanyName
			item.Label = vI.IndustryName
			item.SourceType = 9
			item.SourceId = v.ActivityId
			item.CreateTime = v.CreateTime
			item.ModifyTime = time.Now()
			item.TableName = ""
			//item.RegisterPlatform = v.RegisterPlatform
			items = append(items, item)
		}

		for _, vs := range subjectList {
			if vs.ActivityId != v.ActivityId {
				continue
			}
			haseName = true
			item := new(models.WxUserRaiLabelLog)
			item.UserId = wxUser.UserId
			item.RealName = wxUser.RealName
			item.Mobile = wxUser.Mobile
			item.Email = wxUser.Email
			item.CompanyId = wxUser.CompanyId
			item.CompanyName = wxUser.CompanyName
			item.Label = vs.SubjectName
			item.SourceType = 9
			item.SourceId = v.ActivityId
			item.CreateTime = v.CreateTime
			item.ModifyTime = time.Now()
			//item.RegisterPlatform = v.RegisterPlatform
			items = append(items, item)
		}

		//如果两个标签都没有，就添加临时标签
		if !haseName {
			item := new(models.WxUserRaiLabelLog)
			item.UserId = wxUser.UserId
			item.RealName = wxUser.RealName
			item.Mobile = wxUser.Mobile
			item.Email = wxUser.Email
			item.CompanyId = wxUser.CompanyId
			item.CompanyName = wxUser.CompanyName
			item.Label = mapLabel[v.ActivityId]
			item.SourceType = 9
			item.SourceId = v.ActivityId
			item.CreateTime = v.CreateTime
			item.ModifyTime = time.Now()
			//item.RegisterPlatform = v.RegisterPlatform
			item.TableName = ""
			items = append(items, item)
		}
	}

	for _, v := range ActivityVideoList {
		if mapUser[v.Mobile] == nil || v.Mobile == "" {
			continue
		}
		var haseName bool
		wxUser := mapUser[v.Mobile]
		for _, vI := range industrialList {
			if vI.ActivityId != v.ActivityId {
				continue
			}
			haseName = true
			item := new(models.WxUserRaiLabelLog)
			item.UserId = wxUser.UserId
			item.RealName = wxUser.RealName
			item.Mobile = wxUser.Mobile
			item.Email = wxUser.Email
			item.CompanyId = wxUser.CompanyId
			item.CompanyName = wxUser.CompanyName
			item.Label = vI.IndustryName
			item.SourceType = 9
			item.SourceId = v.ActivityId
			item.CreateTime = v.CreateTime
			item.ModifyTime = time.Now()
			item.TableName = ""
			//item.RegisterPlatform = v.RegisterPlatform
			items = append(items, item)
		}

		for _, vs := range subjectList {
			if vs.ActivityId != v.ActivityId {
				continue
			}
			haseName = true
			item := new(models.WxUserRaiLabelLog)
			item.UserId = wxUser.UserId
			item.RealName = wxUser.RealName
			item.Mobile = wxUser.Mobile
			item.Email = wxUser.Email
			item.CompanyId = wxUser.CompanyId
			item.CompanyName = wxUser.CompanyName
			item.Label = vs.SubjectName
			item.SourceType = 9
			item.SourceId = v.ActivityId
			item.CreateTime = v.CreateTime
			item.ModifyTime = time.Now()
			//item.RegisterPlatform = v.RegisterPlatform
			items = append(items, item)
		}

		//如果两个标签都没有，就添加临时标签
		if !haseName {
			item := new(models.WxUserRaiLabelLog)
			item.UserId = wxUser.UserId
			item.RealName = wxUser.RealName
			item.Mobile = wxUser.Mobile
			item.Email = wxUser.Email
			item.CompanyId = wxUser.CompanyId
			item.CompanyName = wxUser.CompanyName
			item.Label = mapLabel[v.ActivityId]
			item.SourceType = 9
			item.SourceId = v.ActivityId
			item.CreateTime = v.CreateTime
			item.ModifyTime = time.Now()
			//item.RegisterPlatform = v.RegisterPlatform
			item.TableName = ""
			items = append(items, item)
		}
	}
	fmt.Println("initCrm16_5Activity", len(items))
	//return
	var itemsAdd []*models.WxUserRaiLabelLog
	if len(items) > 0 {
		for _, v := range items {
			itemsAdd = append(itemsAdd, v)
			if len(itemsAdd)%2000 == 0 {
				err = models.AddWxUserRaiLabelLogMultiInit(itemsAdd)
				if err != nil {
					return
				}
				itemsAdd = make([]*models.WxUserRaiLabelLog, 0)
			}

		}
	}
	if len(itemsAdd) > 0 {
		err = models.AddWxUserRaiLabelLogMultiInit(itemsAdd)
		if err != nil {
			return
		}
	}
	fmt.Println("endAddWxUserRaiLabelLogMultiInit")
}

func initCrm16_5Article() {
	var condition string
	var pars []interface{}
	condition += `  `
	pars = append(pars)

	listArticleIds, err := models.GetCygxArticleHistoryRecordAllListArticleIdCrm16_5()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("listArticleIds", len(listArticleIds))
	listHave, err := models.GetWxUserRaiArticleLabelCrm16_5()
	if err != nil {
		fmt.Println(err)
		return
	}
	mapArticleId := make(map[int]bool)
	for _, v := range listHave {
		mapArticleId[v.ArticleId] = true
	}
	for k, v := range listArticleIds {
		fmt.Println(k)
		labelArr, sourceType := GetArticlelabelArrByArticleId(v.ArticleId)
		if len(labelArr) == 0 {
			continue
		}
		var items []*models.WxUserRaiArticleLabel
		for _, v2 := range labelArr {
			item := new(models.WxUserRaiArticleLabel)
			item.ArticleId = v.ArticleId
			item.Label = v2
			item.SourceType = sourceType
			item.CreateTime = time.Now()
			items = append(items, item)
		}

		err = models.AddWxUserRaiArticleLabelMultiInit(items)
		time.Sleep(time.Millisecond * 100)
		fmt.Println(err)
	}

}

func initCrm16_5Article2() {
	var condition string
	var pars []interface{}
	condition += `  `
	pars = append(pars)
	//获取提交到会的人员信息
	listArticleIds, err := models.GetCygxArticleHistoryRecordAllListUserIdCrm16_5()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("listArticleIds", len(listArticleIds))

	mapUserId := make(map[string]bool)
	var mobiles []string
	for _, v := range listArticleIds {
		if mapUserId[v.Mobile] {
			continue
		}
		mobiles = append(mobiles, v.Mobile)
		mapUserId[v.Mobile] = true
	}

	listUser, err := models.GetWxUserListByMobileArr(mobiles)
	if err != nil {
		fmt.Println(err)
		return
	}
	mapUser := make(map[string]*models.WxUserItem)
	for _, v := range listUser {
		mapUser[v.Mobile] = v
	}

	listArticleLabel, err := models.GetWxUserRaiArticleLabelAllCrm16_5()
	if err != nil {
		fmt.Println(err)
		return
	}

	mapArticleLabel := make(map[int][]string)
	mapArticleType := make(map[int]int)
	for _, v := range listArticleLabel {
		mapArticleLabel[v.ArticleId] = append(mapArticleLabel[v.ArticleId], v.Label)
		mapArticleType[v.ArticleId] = v.SourceType
	}

	var items []*models.WxUserRaiLabelLog
	for _, v := range listArticleIds {
		if mapUser[v.Mobile] == nil || v.Mobile == "" {
			continue
		}
		if len(mapArticleLabel[v.ArticleId]) == 0 {
			continue
		}
		wxUser := mapUser[v.Mobile]
		for _, vI := range mapArticleLabel[v.ArticleId] {
			item := new(models.WxUserRaiLabelLog)
			item.UserId = wxUser.UserId
			item.RealName = wxUser.RealName
			item.Mobile = wxUser.Mobile
			item.Email = wxUser.Email
			item.CompanyId = wxUser.CompanyId
			item.CompanyName = wxUser.CompanyName
			item.Label = vI
			item.SourceType = mapArticleType[v.ArticleId]
			item.SourceId = v.ArticleId
			item.CreateTime = utils.StrTimeToTime(v.CreateTime)
			item.ModifyTime = time.Now()
			item.TableName = "cygx_article"
			//item.RegisterPlatform = v.RegisterPlatform
			items = append(items, item)
		}

	}
	fmt.Println("items", len(items))

	var itemsAdd []*models.WxUserRaiLabelLog
	if len(items) > 0 {
		for _, v := range items {
			itemsAdd = append(itemsAdd, v)
			if len(itemsAdd)%2000 == 0 {
				err = models.AddWxUserRaiLabelLogMultiInit(itemsAdd)
				if err != nil {
					fmt.Println(err)
					return
				}
				itemsAdd = make([]*models.WxUserRaiLabelLog, 0)
			}

		}
	}
	if len(itemsAdd) > 0 {
		err = models.AddWxUserRaiLabelLogMultiInit(itemsAdd)
		if err != nil {
			fmt.Println(err)
			return
		}
	}
	fmt.Println("endAddWxUserRaiLabelLogMultiInit")

}

//func init() {
//	//initCrm16_5keyWord()
//	//initCrm16_5Activity()
//	////initCrm16_5Article()
//	//initCrm16_5Article2()
//	//initCrm16_5ReportHistory()
//	//initCrm16_5ReportHistory_2()
//	//initCrm16_5Roadshow()
//	//initCrm16_5ActivityVivo()
//	fmt.Println("end RO")
//
//	initCrm16_5wx_user_rai_label()
//
//	fmt.Println("end RO2")
//}

// 记录用户在重点公司单独点了某一个标签
func initCrm16_5ReportHistory_0() {
	var err error
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("SendCygxReportSelectionLogApplyTemplateMsg Err"+err.Error(), 2)
		}
	}()
	var condition string
	var pars []interface{}

	listhistory, err := models.GetCygxReportSelectionSubjectHistory()
	if err != nil {
		fmt.Println(err)
		return
	}
	for kH, vH := range listhistory {
		fmt.Println(kH)
		pars = make([]interface{}, 0)
		condition = ` AND article_id = ?  AND industrial_subject_id = ? AND  industrial_management_id = ? AND  third_id = ? `
		pars = append(pars, vH.ArticleId, vH.IndustrialSubjectId, vH.IndustrialManagementId, vH.ThirdId)
		listLog, e := models.GetCygxReportSelectionLog(condition, pars, 0, 9999)
		if e != nil {
			err = errors.New("GetCygxReportSelectionLog, Err: " + e.Error())
			fmt.Println(err)
			return
		}
		var labelName string
		for _, v2 := range listLog {
			if v2.ThirdId > 0 {
				labelName = v2.ThirdName
			} else if v2.IndustrialSubjectId == 0 && v2.IndustrialManagementId != "" {
				labelName = v2.IndustrialManagementNames
			} else {
				labelName = v2.SubjectName
			}
		}
		err = models.UpdateCygxReportSelectionSubjectHistoryName(labelName, vH.Id)
		if err != nil {
			fmt.Println(err)
			return
		}
	}
	fmt.Println("end")

	return
}

func initCrm16_5ReportHistory() {

	listReportHistory, err := models.GetWxUserRaiCygxReportHistoryRecordCrm16_5()

	if err != nil {
		fmt.Println(err)
		return
	}
	var mobiles []string
	mapMobile := make(map[string]bool)
	for _, v := range listReportHistory {
		if mapMobile[v.Mobile] || v.Mobile == "" {
			continue
		}
		mapMobile[v.Mobile] = true
		mobiles = append(mobiles, v.Mobile)
	}

	listUser, err := models.GetWxUserListByMobileArr(mobiles)

	if err != nil {
		fmt.Println(err)
		return
	}

	mapUser := make(map[string]*models.WxUserItem)

	for _, v := range listUser {
		mapUser[v.Mobile] = v
	}

	var items []*models.WxUserRaiLabelLog
	for _, v := range listReportHistory {
		if mapUser[v.Mobile] == nil || v.Mobile == "" {
			continue
		}
		wxUser := mapUser[v.Mobile]
		item := new(models.WxUserRaiLabelLog)
		item.UserId = wxUser.UserId
		item.RealName = wxUser.RealName
		item.Mobile = wxUser.Mobile
		item.Email = wxUser.Email
		item.CompanyId = wxUser.CompanyId
		item.CompanyName = wxUser.CompanyName
		if v.ReportType == "bgjx" {
			item.Label = "重点推荐"
			item.TableName = "cygx_report_selection"
		} else {
			item.Label = "本周研究汇总"
			item.TableName = "cygx_research_summary"
		}
		item.SourceId = v.ArticleId
		item.SourceType = 8
		item.CreateTime = v.CreateTime
		item.ModifyTime = time.Now()
		item.RegisterPlatform = v.RegisterPlatform
		items = append(items, item)
	}
	fmt.Println("items", len(items))

	var itemsAdd []*models.WxUserRaiLabelLog
	if len(items) > 0 {
		for _, v := range items {
			itemsAdd = append(itemsAdd, v)
			if len(items)%2000 == 0 {
				err = models.AddWxUserRaiLabelLogMultiInit(itemsAdd)
				if err != nil {
					return
				}
				itemsAdd = make([]*models.WxUserRaiLabelLog, 0)
			}
		}
	}
	if len(itemsAdd) > 0 {
		err = models.AddWxUserRaiLabelLogMultiInit(itemsAdd)
		if err != nil {
			return
		}
	}
	fmt.Println("endAddWxUserRaiLabelLogMultiInit")
}

func initCrm16_5Roadshow() {
	var condition string
	var pars []interface{}
	condition = " "
	calendarMeetingUserList, e := roadshow.GetRsCalendarMeetingUserList(condition+"  ORDER BY rs.start_date ASC ", pars)
	if e != nil {
		fmt.Println(e)
		return
	}
	var rsCalendarIds []int
	for _, v := range calendarMeetingUserList {
		rsCalendarIds = append(rsCalendarIds, v.RsCalendarId)
	}

	var mobiles []string
	mapMobile := make(map[string]bool)
	for _, v := range calendarMeetingUserList {
		if mapMobile[v.Mobile] || v.Mobile == "" {
			continue
		}
		mapMobile[v.Mobile] = true
		mobiles = append(mobiles, v.Mobile)
	}

	RsCalendarListInit, e := roadshow.GetRsCalendarListInit(rsCalendarIds)
	if e != nil {
		fmt.Println(e)
		return
	}
	mapRoadshowType := make(map[int]int)
	for _, v := range RsCalendarListInit {
		if v.RoadshowType == "线下" {
			mapRoadshowType[v.RsCalendarId] = 3
		} else {
			mapRoadshowType[v.RsCalendarId] = 5
		}
	}

	listUser, err := models.GetWxUserListByMobileArr(mobiles)

	if err != nil {
		fmt.Println(err)
		return
	}

	mapUser := make(map[string]*models.WxUserItem)

	for _, v := range listUser {
		mapUser[v.Mobile] = v
	}

	var items []*models.WxUserRaiLabelLog
	for _, v := range calendarMeetingUserList {
		if mapUser[v.Mobile] == nil || v.Mobile == "" {
			continue
		}
		wxUser := mapUser[v.Mobile]
		var sourceType int
		sourceType = mapRoadshowType[v.RsCalendarId]

		totalGroup, e := roadshow.GetRsCalendarMeetingLabelGroupByRsCalendarId(v.RsCalendarId)
		if e != nil {
			err = errors.New("GetRsCalendarMeetingLabelGroupByRsCalendarId" + e.Error())
			return
		}
		//var lebelDetail []*cygx.RaiServeTagResp
		var label string
		var labelArr []string
		if totalGroup > 0 {
			listGroup, e := roadshow.GetRsCalendarMeetingLabelGroupListByRsCalendarId(v.RsCalendarId)
			if e != nil {
				err = errors.New("GetRsCalendarMeetingLabelGroupByRsCalendarId" + e.Error())
				return
			}
			var industrialManagementIds []int
			var industrialSubjectIds []int

			mapindustrialManagementName := make(map[int]string)
			mapindustrialSubjectName := make(map[int]string)
			mapCelueName := make(map[int]string)
			for _, vG := range listGroup {
				switch vG.TagType {
				case 1:
					industrialManagementIds = append(industrialManagementIds, vG.TagId)
				case 2:
					industrialSubjectIds = append(industrialSubjectIds, vG.TagId)
				case 3:
					mapCelueName[vG.TagId] = "策略"
				}
			}

			if len(industrialManagementIds) > 0 {
				IndustryList, e := models.GetIndustryListByConditionByIds(industrialManagementIds)
				if e != nil {
					err = errors.New("GetRsCalendarMeetingLabelGroupByRsCalendarId" + e.Error())
					return
				}
				for _, vI := range IndustryList {
					mapindustrialManagementName[vI.IndustrialManagementId] = vI.IndustryName
				}
			}

			if len(industrialSubjectIds) > 0 {
				SubjectList, e := models.GetIndustrialSubjectDetailByIds(industrialSubjectIds)
				if e != nil {
					err = errors.New("GetIndustrialSubjectDetailByIds" + e.Error())
					return
				}
				for _, vS := range SubjectList {
					mapindustrialSubjectName[vS.IndustrialSubjectId] = vS.SubjectName
				}
			}

			for _, vG := range listGroup {
				switch vG.TagType {
				case 1:
					label = mapindustrialManagementName[vG.TagId]
				case 2:
					label = mapindustrialSubjectName[vG.TagId]
				case 3:
					label = mapCelueName[vG.TagId]
				}
				item := new(models.WxUserRaiLabelLog)
				item.UserId = wxUser.UserId
				item.RealName = wxUser.RealName
				item.Mobile = wxUser.Mobile
				item.Email = wxUser.Email
				item.CompanyId = wxUser.CompanyId
				item.CompanyName = wxUser.CompanyName
				item.Label = label
				item.SourceType = sourceType
				item.SourceId = v.RsCalendarId
				item.CreateTime = v.CreateTime
				item.ModifyTime = time.Now()
				//item.RegisterPlatform = log.RegisterPlatform
				item.TableName = ""
				items = append(items, item)
				labelArr = append(labelArr, label)
			}
		}
	}
	fmt.Println("items", len(items))

	var itemsAdd []*models.WxUserRaiLabelLog
	if len(items) > 0 {
		for _, v := range items {
			itemsAdd = append(itemsAdd, v)
			if len(items)%2000 == 0 {
				err = models.AddWxUserRaiLabelLogMultiInit(items)
				if err != nil {
					return
				}
				itemsAdd = make([]*models.WxUserRaiLabelLog, 0)
			}
		}
	}
	if len(itemsAdd) > 0 {
		err = models.AddWxUserRaiLabelLogMultiInit(itemsAdd)
		if err != nil {
			return
		}
	}
	fmt.Println("endAddWxUserRaiLabelLogMultiInit")
}

func initCrm16_5wx_user_rai_label() {

	listAll, err := models.GetWxUserRaiLabelLogAll()
	if err != nil {
		fmt.Println(err)
		return
	}
	mapMobileLabel := make(map[string]bool)
	var items []*models.WxUserRaiLabel
	for _, v := range listAll {
		if mapMobileLabel[fmt.Sprint(v.Mobile, "__", v.Label)] {
			continue
		}
		item := new(models.WxUserRaiLabel)
		item.UserId = v.UserId
		item.RealName = v.RealName
		item.Mobile = v.Mobile
		item.Email = v.Email
		item.CompanyId = v.CompanyId
		item.CompanyName = v.CompanyName
		item.Label = v.Label
		item.SourceId = v.SourceId
		item.SourceType = v.SourceType
		item.CreateTime = v.CreateTime
		item.ModifyTime = v.ModifyTime
		item.RegisterPlatform = v.RegisterPlatform
		item.TableName = v.TableName
		items = append(items, item)

		mapMobileLabel[fmt.Sprint(v.Mobile, "__", v.Label)] = true
	}

	var itemsAdd []*models.WxUserRaiLabel
	if len(items) > 0 {
		for _, v := range items {
			itemsAdd = append(itemsAdd, v)
			if len(itemsAdd)%2000 == 0 {
				err = models.AddWxUserRaiLabelMultiInit(itemsAdd)
				if err != nil {
					return
				}
				itemsAdd = make([]*models.WxUserRaiLabel, 0)
			}
		}
	}
	if len(itemsAdd) > 0 {
		err = models.AddWxUserRaiLabelMultiInit(itemsAdd)
		if err != nil {
			return
		}
	}

	fmt.Println("end initCrm16_5wx_user_rai_label")
}
