package view_log

import (
	"errors"
	"gorm.io/gorm"
	"hongze/hongze_yb/models/tables/company_product"
	"hongze/hongze_yb/models/tables/yb_activity"
	"hongze/hongze_yb/models/tables/yb_view_log"
	"hongze/hongze_yb/services/user"
	"time"
)

func AddViewLog(item *yb_view_log.YbViewLog) (id uint64, err error) {
	//查询对应的客户信息
	companyProduct, err := company_product.GetByCompany2ProductId(item.CompanyId, 1)
	if err != nil {
		return
	}
	//增加记录
	item.CompanyName = companyProduct.CompanyName
	item.CompanyStatus = companyProduct.Status
	item.SellerId = companyProduct.SellerID
	err = item.Create()
	if err != nil {
		return
	}
	return item.Id, nil
}

func UpdateActivityAudioLog(userinfo user.UserInfo, req yb_view_log.ActivityAudioLogStopReq) (err error)  {
	viewLog := new(yb_view_log.YbViewLog)
	viewLog.Id = req.Id
	item, err := viewLog.GetById()
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return
		}
		return
	}
	if item.UserId != userinfo.UserID {
		err = errors.New("用户不一致， 更新日志失败")
		return
	}
	//更新音频停止的时间
	item.StopSeconds = req.StopSeconds
	item.ModifyTime = time.Now()
	err = item.Update([]string{"stop_seconds", "modify_time"})
	return
}

func AddActivityAudioLog(userinfo user.UserInfo, req yb_view_log.ActivityAudioLogAddReq)(resp yb_view_log.ActivityAudioLogAddResp, err error)  {
	//查询报告相关
	var activityDetail *yb_activity.ActivityDetail
	ybViewLog := new(yb_view_log.YbViewLog)
	if req.ExtendId <= 0 {
		err = errors.New("请输入活动ID")
		return
	}
	//根据活动ID查询报告信息
	activityDetail, err = yb_activity.GetDetailById(req.ExtendId)
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return
		}
		return
	}
	if activityDetail.ActivityID == 0 {
		err = errors.New("活动不存在")
		return
	}
	ybViewLog.PrimaryId = req.PrimaryId
	ybViewLog.ExtendId = activityDetail.ActivityID
	ybViewLog.UserId = userinfo.UserID
	ybViewLog.Source = req.Source
	ybViewLog.FromPage = req.FromPage
	ybViewLog.ViewType = 2
	if activityDetail.IsNewReport == 1 {
		ybViewLog.ReportId = activityDetail.ReportId
	}else{
		ybViewLog.OldReportId = activityDetail.ReportId
	}
	ybViewLog.CreateTime = time.Now()
	ybViewLog.ModifyTime = time.Now()
	ybViewLog.CompanyId = userinfo.CompanyID
	id, err := AddViewLog(ybViewLog)
	if err != nil {
		return
	}
	resp.Id = id
	return
}
