package report

import (
	"errors"
	"fmt"
	companyCache "hongze/hongze_yb/cache/company"
	"hongze/hongze_yb/global"
	"hongze/hongze_yb/logic/report"
	"hongze/hongze_yb/models/tables/rddp/report_view_record"
	"hongze/hongze_yb/models/tables/user_view_history"
	"hongze/hongze_yb/services/user"
	"time"
)

func AddViewRecord(userInfo user.UserInfo, reportId int, classifyName string, reportChapterId int) {
	var err error
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("BatchInsertReportView: userId=%d, err:%s", userInfo.UserID, err.Error()))
		}
	}()
	companyInfo, err := companyCache.GetByCompanyId(userInfo.CompanyID)
	if err != nil {
		return
	}
	record := new(report_view_record.ReportViewRecord)
	record.UserId = int(userInfo.UserID)
	record.ReportId = reportId
	record.Mobile = userInfo.Mobile
	record.Email = userInfo.Email
	record.RealName = userInfo.RealName
	record.CompanyName = companyInfo.CompanyName
	record.CreateTime = time.Now()
	record.ReportChapterId = reportChapterId
	err = report_view_record.Create(record)
	if err != nil {
		return
	}
	//修改联系人最后一次阅读报告时间
	err = userInfo.WxUser.SetWxUserReportLastViewTime()

	//新增redis阅读记录
	userViewHistory := &user_view_history.UserViewHistory{
		ViewHistoryID:        uint64(record.Id),
		Mobile:               userInfo.Mobile,
		Email:                userInfo.Email,
		RealName:             userInfo.RealName,
		CompanyName:          companyInfo.CompanyName,
		CreatedTime:          time.Now(),
		UserID:               userInfo.UserID,
		ResearchReportID:     uint64(record.ReportId),
		ResearchReportTypeID: uint64(record.ReportChapterId),
	}
	ret := report.PushViewRecordNewRedisData(userViewHistory, int(userInfo.CompanyID))
	if !ret {
		err = errors.New("缓存添加阅读记录失败")
	}
	return
}
