package services

import (
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/utils"
	"strconv"
)

// 添加历史信息
func AddCygxReportHistoryRecord(item *models.CygxReportHistoryRecord) (err error) {
	//defer func() {
	//	if err != nil {
	//		go utils.SendAlarmMsg("产品内测用户浏览信息记录失败"+err.Error(), 2)
	//	}
	//}()
	if item.StopTime >= 5 {
		_, err = models.AddCygxReportHistoryRecord(item)
		if err != nil {
			go utils.SendAlarmMsg("报告精选用户浏览信息记录失败"+err.Error()+"报告类型"+item.ReportType+"报告ID："+strconv.Itoa(item.ArticleId), 2)
		}
	}

	historyRecordLog := new(models.CygxReportHistoryRecordLog)
	historyRecordLog.UserId = item.UserId
	historyRecordLog.ArticleId = historyRecordLog.ArticleId
	historyRecordLog.CreateTime = historyRecordLog.CreateTime
	historyRecordLog.Mobile = historyRecordLog.Mobile
	historyRecordLog.Email = historyRecordLog.Email
	historyRecordLog.CompanyId = historyRecordLog.CompanyId
	historyRecordLog.CompanyName = historyRecordLog.CompanyName
	historyRecordLog.StopTime = historyRecordLog.StopTime
	historyRecordLog.OutType = historyRecordLog.OutType
	historyRecordLog.ReportType = historyRecordLog.ReportType
	historyRecordLog.RegisterPlatform = historyRecordLog.RegisterPlatform

	_, err = models.AddCygxReportHistoryRecordLog(historyRecordLog)
	if err != nil {
		go utils.SendAlarmMsg("报告精选用户浏览信息日志记录失败"+err.Error()+"报告类型"+item.ReportType+"报告ID："+strconv.Itoa(item.ArticleId), 2)
	}
	return
}

// 获取 报告精选，本周研究汇总、上周纪要汇总Pv 阅读数据
func GetCygxReportHistoryRecordListMap(articleIds []int, reportType string) (mapPv map[int]int) {
	var err error
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("获取产品内测的阅读数据，信息失败，Err："+err.Error(), 3)
		}
	}()
	lenArr := len(articleIds)
	if lenArr == 0 {
		return
	}
	var condition string
	var pars []interface{}
	condition = ` AND article_id IN (` + utils.GetOrmInReplace(lenArr) + `) AND  report_type = ?`
	pars = append(pars, articleIds, reportType)
	list, e := models.GetCygxReportHistoryRecordListPv(condition, pars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		return
	}
	mapPv = make(map[int]int, 0)
	for _, v := range list {
		mapPv[v.ArticleId] = v.Pv
	}
	return
}
