package community

import (
	"errors"
	"hongze/hongze_yb/models/response"
	"hongze/hongze_yb/models/tables/company_product"
	"hongze/hongze_yb/models/tables/yb_community_video"
	"hongze/hongze_yb/models/tables/yb_community_video_play_log"
	"hongze/hongze_yb/services/user"
	"hongze/hongze_yb/utils"
	"time"
)

// GetVideoList 获取视频列表
func GetVideoList(pageIndex, pageSize, videoId, varietyTagId int, keywords string) (resp []*response.CommunityVideoItem, err error) {
	condition := make(map[string]interface{})
	// 分享点进来的直接定位到具体视频
	if videoId > 0 {
		condition["community_video_id ="] = videoId
	} else {
		if varietyTagId > 0 {
			condition["variety_tag_id ="] = varietyTagId
		}
		if keywords != "" {
			condition["title like"] = "%" + keywords + "%"
		}
	}
	resp = make([]*response.CommunityVideoItem, 0)
	list, e := yb_community_video.GetPageListByCondition(condition, pageIndex, pageSize)
	if e != nil {
		err = errors.New("获取视频列表失败, Err:" + e.Error())
		return
	}
	if len(list) <= 0 {
		return
	}
	for _, v := range list {
		item := &response.CommunityVideoItem{
			CommunityVideoID:    v.CommunityVideoID,
			Title:               v.Title,
			VarietyTagId:        v.VarietyTagId,
			VarietyTagName:      v.VarietyTagName,
			CoverImgUrl:         v.CoverImgURL,
			VideoUrl:            v.VideoURL,
			VideoSeconds:        v.VideoSeconds,
			PublishState:        v.PublishState,
			PublishTime:         v.PublishTime.Format(utils.FormatDateTime),
			CreateTime:          v.CreateTime.Format(utils.FormatDateTime),
			ModifyTime:          v.ModifyTime.Format(utils.FormatDateTime),
			ChartPermissionName: v.VarietyTagName,
		}
		resp = append(resp, item)
	}
	return
}

// SaveVideoPlayLog 记录用户播放视频日志
func SaveVideoPlayLog(userInfo user.UserInfo, videoId, sourceAgent int) (errMsg string, err error) {
	video, e := yb_community_video.GetItemById(videoId)
	if e != nil {
		errMsg = "视频不存在或未发布"
		err = errors.New("获取视频信息失败, Err: " + e.Error())
		return
	}
	companyInfo, e := company_product.GetByCompany2ProductId(userInfo.CompanyID, 1)
	if e != nil && e != utils.ErrNoRow {
		errMsg = "保存失败"
		err = errors.New("获取客户信息失败, Err: " + e.Error())
		return
	}
	companyName := "潜在客户"
	companyStatus := "潜在"
	if companyInfo != nil && companyInfo.CompanyID > 0 {
		companyName = companyInfo.CompanyName
		companyStatus = companyInfo.Status
	}
	item := &yb_community_video_play_log.YbCommunityVideoPlayLog{
		CommunityVideoID: video.CommunityVideoID,
		UserID:           int(userInfo.UserID),
		Mobile:           userInfo.Mobile,
		RealName:         userInfo.RealName,
		NickName:         userInfo.NickName,
		CompanyID:        int(userInfo.CompanyID),
		CompanyName:      companyName,
		CompanyStatus:    companyStatus,
		SourceAgent:      sourceAgent,
		SellerID:         companyInfo.SellerID,
		CreateTime:       time.Now().Local(),
	}
	if e = item.Create(); e != nil {
		errMsg = "操作失败"
		err = errors.New("新增播放视频日志失败, Err:" + e.Error())
		return
	}
	return
}
