package services

import (
	"errors"
	"fmt"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/utils"
	"time"
)

// 记录产业时间线的点击记录
func AddCygxTimelineLog(user *models.WxUserItem, industrialManagementId int) (err error) {
	if user.UserId == 0 {
		return
	}
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("记录产业时间线的点击记录 失败 AddCygxTimelineLog Err:"+err.Error(), "userId:", user.UserId, "industrialManagementId:", industrialManagementId), 2)
		}
	}()
	//获取销售信息
	sellerItem, e := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetSellerByCompanyIdCheckFicc, Err: " + e.Error())
		return
	}
	if sellerItem == nil {
		return
	}

	//判断一个用户是否阅读过 某一篇研选专栏
	totalRecord, e := models.GetCygxTimelineLogCountByUser(user.UserId, industrialManagementId)
	if e != nil {
		err = errors.New("GetCygxTimelineLogCountByUser, Err: " + e.Error())
		return
	}
	if totalRecord == 0 {
		item := new(models.CygxTimelineLog)
		item.UserId = user.UserId
		item.Mobile = user.Mobile
		item.Email = user.Email
		item.CompanyId = user.CompanyId
		item.CompanyName = user.CompanyName
		item.RealName = user.RealName
		item.CreateTime = time.Now()
		item.ModifyTime = time.Now()
		item.IndustrialManagementId = industrialManagementId
		_, e = models.AddCygxTimelineLog(item) // 添加历史记录
	} else {
		//更新时间线下对应产业的阅读时间
		e = models.UpdateCygxTimelineLogModifyTime(user.UserId, industrialManagementId)
		if e != nil {
			err = errors.New("UpdateCygxTimelineLogModifyTime, Err: " + e.Error())
			return
		}
	}
	return
}
