package cygx

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

// 添加用户活动到会标签到Redis
func ActivityUserLabelLogAdd(activityId int, userIdArr []int) (err error) {
	if len(userIdArr) == 0 {
		return
	}
	defer func() {
		if err != nil {
			fmt.Println(err)
			msg := fmt.Sprint("activityId:", activityId, "mobile:", userIdArr)
			go alarm_msg.SendAlarmMsg("添加用户活动到会标签到Redis，写入Redis队列消息失败："+err.Error()+msg, 2)
		}
	}()
	var condition string
	var pars []interface{}
	condition = ` AND activity_id = ?  `
	pars = append(pars, activityId)
	total, e := cygx.GetCygxIndustrialActivityGroupManagementCount(condition+"  AND  source = 1 ", pars)
	if e != nil {
		err = errors.New("GetCygxIndustrialActivityGroupManagementCount" + e.Error())
		return
	}
	if total == 0 {
		//没有关联产业的活动不做标签处理
		return
	}

	industrialList, e := cygx.GetCygxIndustrialActivityGroupManagementList(condition+"  AND  source = 1 ", pars)
	if e != nil {
		err = errors.New("GetCygxIndustrialActivityGroupManagementList, Err: " + e.Error())
		return
	}

	//如果有行产业归类就按照产业报告处理
	var topCond string
	var topPars []interface{}
	var industrialManagementIds []int

	for _, v := range industrialList {
		industrialManagementIds = append(industrialManagementIds, v.IndustrialManagementId)
	}
	idsLen := len(industrialManagementIds)
	if idsLen > 0 {
		topCond = ` AND industrial_management_id IN (` + utils.GetOrmInReplace(idsLen) + `)`
		topPars = append(topPars, industrialManagementIds)
	} else {
		return
	}
	industrNamelist, e := cygx.GetTopOneMonthArtReadNumIndustryAll(topCond, topPars)
	if e != nil {
		err = errors.New("GetTopOneMonthArtReadNumIndustryAll, Err: " + e.Error())
		return
	}

	userList, e := models.GetWxUserByUserIds(userIdArr)
	if e != nil {
		err = errors.New("GetWxUserByOutboundMobiles" + e.Error())
		return
	}
	listActivityHistory, e := cygx.GetCygxUserLabelActivity(condition, pars, 0, 9999)
	if e != nil {
		err = errors.New("GetCygxUserLabelActivity" + e.Error())
		return
	}
	activityHistoryMap := make(map[int]bool)
	for _, v := range listActivityHistory {
		activityHistoryMap[v.UserId] = true
	}
	var items []*cygx.CygxUserLabelActivity
	for _, user := range userList {
		//已经提交到会的活动写入标签的不做二次添加处理
		if activityHistoryMap[int(user.UserId)] {
			continue
		}
		// SourceType 1：文章阅读、 2产业关注、3：活动到会、4系列关注、5专项调研活动到会。
		log := &cygx.CygxUserLabelLogRedis{UserId: int(user.UserId), SourceId: activityId, SourceType: 3, CreateTime: time.Now()}
		if utils.Re == nil {
			err := utils.Rc.LPush(utils.CYGX_USER_KEY_LABEL, log)
			if err != nil {
				fmt.Println("CygxUserLabelLogRedis LPush Err:" + err.Error())
			}
		}
		for _, industr := range industrNamelist {
			item := new(cygx.CygxUserLabelActivity)
			item.UserId = int(user.UserId)
			item.CompanyId = user.CompanyId
			item.RealName = user.RealName
			item.Mobile = user.Mobile
			item.Email = user.Email
			item.ActivityId = activityId
			item.IndustrialManagementId = industr.IndustrialManagementId
			item.Label = industr.IndustryName
			item.CreateTime = time.Now()
			item.ModifyTime = time.Now()
			items = append(items, item)
		}
	}
	if len(items) > 0 {
		_, err = cygx.AddCygxUserLabelActivityList(items)
	}
	return
}

// 添加用户活动到会标签到Redis
func ActivitySpecialUserLabelLogAdd(activityId int, userIdArr []int) (err error) {
	if len(userIdArr) == 0 {
		return
	}
	defer func() {
		if err != nil {
			fmt.Println(err)
			msg := fmt.Sprint("activityId:", activityId, "mobile:", userIdArr)
			go alarm_msg.SendAlarmMsg("添加用户专项调研活动到会标签到Redis，写入Redis队列消息失败："+err.Error()+msg, 2)
		}
	}()
	var condition string
	var pars []interface{}
	condition = ` AND activity_id = ?  `
	pars = append(pars, activityId)
	total, e := cygx.GetCygxIndustrialActivityGroupManagementCount(condition+"  AND  source = 2 ", pars)
	if e != nil {
		err = errors.New("GetCygxIndustrialActivityGroupManagementCount" + e.Error())
		return
	}
	if total == 0 {
		//没有关联产业的活动不做标签处理
		return
	}

	industrialList, e := cygx.GetCygxIndustrialActivityGroupManagementList(condition+"  AND  source = 2 ", pars)
	if e != nil {
		err = errors.New("GetCygxIndustrialActivityGroupManagementList, Err: " + e.Error())
		return
	}

	//如果有行产业归类就按照产业报告处理
	var topCond string
	var topPars []interface{}
	var industrialManagementIds []int

	for _, v := range industrialList {
		industrialManagementIds = append(industrialManagementIds, v.IndustrialManagementId)
	}
	idsLen := len(industrialManagementIds)
	if idsLen > 0 {
		topCond = ` AND industrial_management_id IN (` + utils.GetOrmInReplace(idsLen) + `)`
		topPars = append(topPars, industrialManagementIds)
	} else {
		return
	}
	industrNamelist, e := cygx.GetTopOneMonthArtReadNumIndustryAll(topCond, topPars)
	if e != nil {
		err = errors.New("GetTopOneMonthArtReadNumIndustryAll, Err: " + e.Error())
		return
	}

	userList, e := models.GetWxUserByUserIds(userIdArr)
	if e != nil {
		err = errors.New("GetWxUserByOutboundMobiles" + e.Error())
		return
	}
	listActivityHistory, e := cygx.GetCygxUserLabelActivitySpecial(condition, pars, 0, 9999)
	if e != nil {
		err = errors.New("GetCygxUserLabelActivity" + e.Error())
		return
	}
	activityHistoryMap := make(map[int]bool)
	for _, v := range listActivityHistory {
		activityHistoryMap[v.UserId] = true
	}
	var items []*cygx.CygxUserLabelActivitySpecial
	for _, user := range userList {
		//已经提交到会的活动写入标签的不做二次添加处理
		if activityHistoryMap[int(user.UserId)] {
			continue
		}
		// SourceType 1：文章阅读、 2产业关注、3：活动到会、4系列关注、5专项调研活动到会。
		log := &cygx.CygxUserLabelLogRedis{UserId: int(user.UserId), SourceId: activityId, SourceType: 5, CreateTime: time.Now()}
		if utils.Re == nil {
			err := utils.Rc.LPush(utils.CYGX_USER_KEY_LABEL, log)
			if err != nil {
				fmt.Println("CygxUserLabelLogRedis LPush Err:" + err.Error())
			}
		}
		for _, industr := range industrNamelist {
			item := new(cygx.CygxUserLabelActivitySpecial)
			item.UserId = int(user.UserId)
			item.CompanyId = user.CompanyId
			item.RealName = user.RealName
			item.Mobile = user.Mobile
			item.Email = user.Email
			item.ActivityId = activityId
			item.IndustrialManagementId = industr.IndustrialManagementId
			item.Label = industr.IndustryName
			item.CreateTime = time.Now()
			item.ModifyTime = time.Now()
			items = append(items, item)
		}
	}
	if len(items) > 0 {
		_, err = cygx.AddCygxUserLabelActivitySpecialList(items)
	}
	return
}

// 用户关注产业更新相关标签到Redis
func IndustryFllowUserLabelLogAdd(industrialManagementId, count, uid int) (err error) {
	var isFllow int
	if count == 0 {
		isFllow = 1
	} else {
		isFllow = 0
	}
	defer func() {
		if err != nil {
			fmt.Println(err)
			msg := fmt.Sprint("industrialManagementId:", industrialManagementId, "isFllow:", isFllow, "userId:", uid)
			go alarm_msg.SendAlarmMsg("用户关注产业更新相关标签，写入Redis队列消息失败："+err.Error()+msg, 2)
		}
	}()
	log := &cygx.CygxUserLabelLogRedis{UserId: uid, SourceId: industrialManagementId, SourceType: 2, IsFllow: isFllow, CreateTime: time.Now()}
	if utils.Re == nil {
		err := utils.Rc.LPush(utils.CYGX_USER_KEY_LABEL, log)
		if err != nil {
			fmt.Println("RecordNewLogs LPush Err:" + err.Error())
		}
	}
	return
}

// GetUserInteractionNumMap 根据用户ID 获取对应的用户互动量
func GetUserInteractionNumMap(userIds []int) (mapResp map[int]int) {
	lenArr := len(userIds)
	if lenArr == 0 {
		return
	}
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg(fmt.Sprint("GetUserInteractionNumMap 根据用户ID 获取对应的用户互动量 失败 userIds", userIds, err.Error()), 2)
		}
	}()
	var userIdsArr []string
	for _, v := range userIds {
		userIdsArr = append(userIdsArr, strconv.Itoa(v))
	}
	userIdstr := strings.Join(userIdsArr, ",")
	list, e := cygx.GetCygxCompanyUserListSplit(userIdstr)
	if e != nil {
		err = errors.New("GetCygxCompanyUserListSplit, Err: " + e.Error())
		return
	}
	mapResp = make(map[int]int, 0)
	for k, v := range list {
		mapResp[int(v.UserId)] = list[k].HistoryNum + list[k].CountNum + list[k].IndustryFllowNum + list[k].DepartmentFollowNum + list[k].KeyWordNum + list[k].OnLineNum + list[k].OfficeNum + list[k].ChartNum + list[k].TripNum + list[k].RoadshowVideoNum + list[k].ActivityVideoNum + list[k].ActivityVoiceNum + list[k].YanxuanspecialNum
	}
	return
}

// 预处理1v1路演的参会人员信息
func HandleListRsCalendar(list []*roadshow.RsCalendarMeetingUserByRai) (items []*cygx.UserInteraction, err error) {
	if len(list) == 0 {
		return
	}
	var rsCalendarIds []int
	for _, v := range list {
		rsCalendarIds = append(rsCalendarIds, v.RsCalendarId)
	}

	mapRsCalendarLabel := make(map[int][]string) //1v1 路演标签
	mapRsCalendarLabel = GetRsCalendarLabelByRsCalendarIds(rsCalendarIds)

	//获取研究员信息
	researchers, err := roadshow.GetRsCalendarResearcherListByIds(rsCalendarIds)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return
	}
	mapResearcherName := make(map[int][]string)
	for _, v := range researchers {
		mapResearcherName[v.RsCalendarId] = append(mapResearcherName[v.RsCalendarId], v.ResearcherName)
	}

	//listGroup, err := roadshow.GetRsCalendarMeetingLabelGroupDetailByRsCalendarIds(rsCalendarIds)
	//if err != nil && err.Error() != utils.ErrNoRow() {
	//	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 {
	//	fmt.Println(v)
	//	switch v.TagType {
	//	case 1:
	//		industrialManagementIds = append(industrialManagementIds, v.TagId)
	//	case 2:
	//		industrialSubjectIds = append(industrialSubjectIds, v.TagId)
	//	case 3:
	//		mapCelueName[v.RsCalendarId] = "策略"
	//	}
	//}

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

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

	//mapGroupindustrialManagementName := make(map[int][]string)
	//mapGroupindustrialSubjectName := make(map[int][]string)
	//for _, v := range listGroup {
	//	switch v.TagType {
	//	case 1:
	//		mapGroupindustrialManagementName[v.RsCalendarId] = append(mapGroupindustrialManagementName[v.RsCalendarId], mapindustrialManagementName[v.TagId])
	//	case 2:
	//		mapGroupindustrialSubjectName[v.RsCalendarId] = append(mapGroupindustrialSubjectName[v.RsCalendarId], mapindustrialSubjectName[v.TagId])
	//	}
	//}

	for _, v := range list {
		item := new(cygx.UserInteraction)
		item.UserId = v.UserId
		item.RealName = v.RealName
		item.Mobile = v.Mobile
		item.CompanyId = v.CompanyId
		item.CompanyName = v.CompanyName
		//switch v.TagType {
		//case 1:
		//	item.LabelKeyWord = strings.Join(mapGroupindustrialManagementName[v.RsCalendarId], ",")
		//case 2:
		//	item.LabelKeyWord = strings.Join(mapGroupindustrialSubjectName[v.RsCalendarId], ",")
		//case 3:
		//	item.LabelKeyWord = mapCelueName[v.RsCalendarId]
		//}

		item.LabelKeyWord = strings.Join(mapRsCalendarLabel[v.RsCalendarId], ",")
		item.ActivityTimeText = v.StartDate + "（" + v.StartWeek + "）" + v.StartTime + "-" + v.EndTime
		item.ResearcherName = strings.Join(mapResearcherName[v.RsCalendarId], ",")
		items = append(items, item)
	}

	return
}

// 获取1V1路演标签信息
func GetRsCalendarLabelByRsCalendarIds(rsCalendarIds []int) (respMap map[int][]string) {
	if len(rsCalendarIds) == 0 {
		return
	}
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg(fmt.Sprint("获取1V1路演标签信息 失败 GetRsCalendarLabelByRsCalendarIds rsCalendarIds: ", rsCalendarIds, err.Error()), 2)
		}
	}()

	listEmail, err := cygx.GetAskEmail()
	if err != nil && err.Error() != utils.ErrNoRow() {
		return
	}
	var ceLueResearcherName []string
	var guShouResearcherName []string
	for _, v := range listEmail {
		if v.ChartPermissionName == utils.CE_LUE_NAME {
			ceLueResearcherName = append(ceLueResearcherName, v.Name)
		}
		if v.ChartPermissionName == utils.GU_SHOU_NAME {
			guShouResearcherName = append(guShouResearcherName, v.Name)
		}
	}

	//获取研究员信息
	researchers, err := roadshow.GetRsCalendarResearcherListByIds(rsCalendarIds)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return
	}
	mapResearcherName := make(map[int][]string)
	for _, v := range researchers {
		if utils.InArrayByStr(ceLueResearcherName, v.ResearcherName) {
			mapResearcherName[v.RsCalendarId] = append(mapResearcherName[v.RsCalendarId], "策略")
		}
		if utils.InArrayByStr(guShouResearcherName, v.ResearcherName) {
			mapResearcherName[v.RsCalendarId] = append(mapResearcherName[v.RsCalendarId], "固收")
		}
	}

	listGroup, err := roadshow.GetRsCalendarMeetingLabelGroupDetailByRsCalendarIds(rsCalendarIds)
	if err != nil && err.Error() != utils.ErrNoRow() {
		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.RsCalendarId] = strings.Join(mapResearcherName[v.RsCalendarId], ",")
		}
	}

	if len(industrialManagementIds) > 0 {
		IndustryList, e := cygx.GetIndustryListByConditionByIds(industrialManagementIds)
		if e != nil {
			err = errors.New("GetIndustryListByConditionByIds" + e.Error())
			return
		}

		for _, v := range IndustryList {
			mapindustrialManagementName[v.IndustrialManagementId] = v.IndustryName
		}
	}

	if len(industrialSubjectIds) > 0 {
		SubjectList, e := cygx.GetIndustrialSubjectDetailByIds(industrialSubjectIds)
		if e != nil {
			err = errors.New("GetIndustryListByConditionByIds" + e.Error())
			return
		}
		for _, v := range SubjectList {
			mapindustrialSubjectName[v.IndustrialSubjectId] = v.SubjectName
		}
	}
	respMap = make(map[int][]string, 0)
	for _, v := range listGroup {
		switch v.TagType {
		case 1:
			respMap[v.RsCalendarId] = append(respMap[v.RsCalendarId], mapindustrialManagementName[v.TagId])
		case 2:
			respMap[v.RsCalendarId] = append(respMap[v.RsCalendarId], mapindustrialSubjectName[v.TagId])
		case 3:
			respMap[v.RsCalendarId] = append(respMap[v.RsCalendarId], mapCelueName[v.RsCalendarId])
		}
	}

	for _, v := range rsCalendarIds {
		if len(respMap[v]) == 0 && len(mapResearcherName[v]) > 0 {
			respMap[v] = mapResearcherName[v]
		}
	}
	return
}
