package cygx

import (
	"errors"
	"fmt"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"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
}
