package yb

import (
	"errors"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/yb"
	"hongze/hz_crm_api/models/yb/response"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

// GetCommunityVideoList 视频列表
func GetCommunityVideoList(condition string, pars []interface{}, orderStr string, startSize, pageSize int) (total int, resp *response.CommunityVideoListResp, err error) {
	resp = new(response.CommunityVideoListResp)
	total, list, e := yb.GetCommunityVideoList(condition, pars, orderStr, startSize, pageSize)
	if e != nil {
		err = errors.New("获取问题列表失败 Err:" + e.Error())
		return
	}
	if len(list) == 0 {
		return
	}
	respList := make([]*response.CommunityVideoItem, 0)
	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,
			SendThsState:      v.SendThsState,
			SendTemplateState: v.SendTemplateState,
			CreateTime:        v.CreateTime.Format(utils.FormatDateTime),
			ModifyTime:        v.ModifyTime.Format(utils.FormatDateTime),
			ClickNum:          v.ClickNum,
		}
		respList = append(respList, item)
	}
	resp.List = respList
	return
}

// SaveCommunityVideo 保存视频
func SaveCommunityVideo(videoId, varietyTagId int, title, coverImgUrl, videoUrl, videoSeconds string) (resp *response.CommunityVideoItem, errMsg string, err error) {
	//chartPermissionName := ""
	varietyTagName := ""
	if varietyTagId > 0 {
		varietyTag, e := models.GetVarietyTagById(varietyTagId)
		//chartPermission, e := models.GetChartPermissionById(chartPermissionId)
		if e != nil {
			errMsg = "品种信息有误"
			err = errors.New("获取品种信息失败, Err:" + e.Error())
			return
		}
		varietyTagName = varietyTag.TagName
	}
	resp = new(response.CommunityVideoItem)
	// 更新
	nowTime := time.Now().Local()
	if videoId > 0 {
		item, e := yb.GetVideoById(videoId)
		if e != nil {
			errMsg = "视频信息有误"
			err = errors.New("获取视频信息失败, Err:" + e.Error())
			return
		}
		updateCols := make([]string, 0)
		updateCols = append(updateCols, "Title", "VarietyTagId", "VarietyTagName", "CoverImgUrl", "VideoUrl", "VideoSeconds", "ModifyTime")
		item.Title = title
		item.VarietyTagId = varietyTagId
		item.VarietyTagName = varietyTagName
		item.CoverImgUrl = coverImgUrl
		item.VideoUrl = videoUrl
		item.VideoSeconds = videoSeconds
		item.ModifyTime = nowTime
		if e := item.Update(updateCols); e != nil {
			errMsg = "更新失败"
			err = errors.New("更新视频信息失败, Err:" + e.Error())
		}
		resp = formatCommunityVideoItem(item)
		return
	}
	// 新增
	videoItem := &yb.CommunityVideo{
		Title:          title,
		VarietyTagId:   varietyTagId,
		VarietyTagName: varietyTagName,
		CoverImgUrl:    coverImgUrl,
		VideoUrl:       videoUrl,
		VideoSeconds:   videoSeconds,
		CreateTime:     nowTime,
		ModifyTime:     nowTime,
	}
	if _, e := videoItem.Add(); e != nil {
		errMsg = "新增失败"
		err = errors.New("新增视频信息失败, Err:" + e.Error())
	}
	resp = formatCommunityVideoItem(videoItem)
	return
}

func formatCommunityVideoItem(item *yb.CommunityVideo) (resp *response.CommunityVideoItem) {
	resp = new(response.CommunityVideoItem)
	if item != nil {
		resp.CommunityVideoId = item.CommunityVideoId
		resp.Title = item.Title
		resp.VarietyTagId = item.VarietyTagId
		resp.VarietyTagName = item.VarietyTagName
		resp.CoverImgUrl = item.CoverImgUrl
		resp.VideoUrl = item.VideoUrl
		resp.VideoSeconds = item.VideoSeconds
		resp.PublishState = item.PublishState
		resp.SendThsState = item.SendThsState
		resp.SendTemplateState = item.SendTemplateState
		resp.CreateTime = item.CreateTime.Format(utils.FormatDateTime)
		resp.ModifyTime = item.ModifyTime.Format(utils.FormatDateTime)
	}
	return
}

// SoftDeleteCommunityVideo 删除视频
func SoftDeleteCommunityVideo(videoId int) (errMsg string, err error) {
	if _, e := yb.GetVideoById(videoId); e != nil {
		errMsg = "视频信息有误"
		err = errors.New("获取视频信息失败, Err:" + e.Error())
		return
	}
	if e := yb.DeleteVideo(videoId); e != nil {
		errMsg = "删除失败"
		err = errors.New("删除视频失败, Err:" + e.Error())
	}
	return
}

// PublishCommunityVideo 发布/取消发布视频
func PublishCommunityVideo(videoId, publishState int) (errMsg string, err error) {
	item, e := yb.GetVideoById(videoId)
	if e != nil {
		errMsg = "视频信息有误"
		err = errors.New("获取视频信息失败, Err:" + e.Error())
		return
	}
	nowTime := time.Now().Local()
	updateCols := make([]string, 0)
	updateCols = append(updateCols, "PublishState", "ModifyTime")
	if publishState == 1 {
		updateCols = append(updateCols, "PublishTime")
		item.PublishTime = nowTime
	}
	item.PublishState = publishState
	item.ModifyTime = nowTime
	if e := item.Update(updateCols); e != nil {
		errMsg = "操作失败"
		err = errors.New("更新视频信息失败, Err:" + e.Error())
	}
	return
}

// SendCommunityVideoThsMsg 推送视频客群消息
func SendCommunityVideoThsMsg(videoId int) (errMsg string, err error) {
	item, e := yb.GetVideoById(videoId)
	if e != nil {
		errMsg = "视频信息有误"
		err = errors.New("获取视频信息失败, Err:" + e.Error())
		return
	}
	if item.PublishState != 1 {
		errMsg = "视频未发布, 不可推送"
		err = errors.New("视频未发布, 不可推送")
		return
	}
	if item.SendThsState != 0 {
		errMsg = "请勿重复推送"
		err = errors.New("请勿重复推送客群消息")
		return
	}
	nowTime := time.Now().Local()
	updateCols := make([]string, 0)
	updateCols = append(updateCols, "SendThsState", "SendThsTime")
	item.SendThsState = 1
	item.SendThsTime = nowTime
	if e := item.Update(updateCols); e != nil {
		err = errors.New("更新视频信息失败, Err:" + e.Error())
	}
	//go func() {
	//	_ = services.SendYbCommunityVideoThs(item.CommunityVideoId, item.Title)
	//}()
	return
}

func GetVideoPlayLogList(videoId, videoType, startSize, pageSize, sortType int) (pageTotal int64, resp *response.VideoPlayLogListResp, err error) {
	var videoInfo *yb.CommunityVideo
	var RoadVideoInfo *yb.RoadVideo
	var title string
	if videoType == 1 {
		videoInfo, err = yb.GetVideoById(videoId)
		if err != nil {
			err = errors.New("视频信息有误 Err:" + err.Error())
			return
		}
		title = videoInfo.Title
	} else {
		RoadVideoInfo, err = yb.GetRoadVideoById(videoId)
		if err != nil {
			err = errors.New("视频信息有误 Err:" + err.Error())
			return
		}
		title = RoadVideoInfo.Title
	}

	// 播放时长排序：默认倒序; 1-倒序; 2-正序
	orderRule := ``
	if sortType == 2 {
		orderRule = ` ORDER BY stop_seconds ASC, create_time DESC`
	}

	resp = new(response.VideoPlayLogListResp)
	resp.Title = title
	list, e := yb.GetVideoPlayLogListByVideoIdV2(videoId, videoType, startSize, pageSize, orderRule)
	if e != nil {
		err = errors.New("获取视频列表失败 Err:" + e.Error())
		return
	}
	//pageTotal, err = yb.GetVideoPlayListTotalByVideoId(videoId, videoType)
	//if err != nil {
	//	err = errors.New("查询视频列表总点击量失败 Err:" + err.Error())
	//	return
	//}

	count, err := yb.GetVideoPlayTotalByVideoIdV2(videoId, videoType)
	if err != nil {
		err = errors.New("查询视频总点击量失败 Err:" + err.Error())
		return
	}
	pageTotal = count
	resp.Count = int(count)

	if len(list) == 0 {
		return
	}
	userIds := ""
	for _, v := range list {
		userIds += ", " + (strconv.Itoa(v.UserId))
	}
	companyUsersMap := make(map[int]*company.CompanyUser)
	if userIds != "" {
		userIds = strings.Trim(userIds, ",")
		//查询用户相关的客户信息
		companyUserList, tErr := company.GetFiccCompanyUserByUserIds(userIds)
		if tErr != nil {
			err = errors.New("获取客户信息失败 Err:" + tErr.Error())
			return
		}
		for _, v := range companyUserList {
			companyUsersMap[int(v.UserId)] = v
		}
	}
	respList := make([]*response.VideoPlayLogListItem, 0)
	for _, v := range list {
		tmp := new(response.VideoPlayLogListItem)
		tmp.UserId = v.UserId
		tmp.CreateTime = v.CreateTime
		tmp.StopSeconds = v.StopSeconds
		//tmp.ClickNum = v.ClickNum
		//tmp.LastCreateTime = v.LastCreateTime
		tmp.SourceAgent = v.NewSourceAgent
		if u, ok := companyUsersMap[v.UserId]; ok {
			tmp.RealName = u.RealName
			tmp.CompanyName = u.CompanyName
			tmp.CompanyStatus = u.Status
			tmp.CompanyId = u.CompanyId
		}
		respList = append(respList, tmp)
	}

	resp.List = respList

	return
}

// SendCommunityVideoTemplateMsg 推送模板消息
func SendCommunityVideoTemplateMsg(videoId int) (errMsg string, err error) {
	item, e := yb.GetVideoById(videoId)
	if e != nil {
		errMsg = "视频信息有误"
		err = errors.New("获取视频信息失败, Err:" + e.Error())
		return
	}
	if item.PublishState != 1 {
		errMsg = "视频未发布, 不可推送"
		err = errors.New("视频未发布, 不可推送")
		return
	}
	if item.SendTemplateState != 0 {
		errMsg = "请勿重复推送"
		err = errors.New("请勿重复推送模板消息")
		return
	}
	updateCols := make([]string, 0)
	updateCols = append(updateCols, "SendTemplateState", "SendTemplateTime")
	item.SendTemplateState = 1
	item.SendTemplateTime = time.Now().Local()
	if e := item.Update(updateCols); e != nil {
		err = errors.New("更新视频信息失败, Err:" + e.Error())
	}
	go func() {
		_ = services.SendYbCommunityVideoWxMsg(item.CommunityVideoId, item.VarietyTagName, item.Title, item.PublishTime.Format(utils.FormatDateTime))
	}()
	return
}

// GetCommunityVideoCoverList 封面库列表
func GetCommunityVideoCoverList(condition string, pars []interface{}, orderRule string, startSize, pageSize int) (total int, resp *response.CommunityVideoCoverListResp, err error) {
	resp = new(response.CommunityVideoCoverListResp)
	total, list, e := yb.GetCommunityVideoCoverPageList(condition, pars, orderRule, startSize, pageSize)
	if e != nil {
		err = errors.New("获取封面库列表失败, Err:" + e.Error())
		return
	}
	if len(list) == 0 {
		return
	}
	respList := make([]*response.CommunityVideoCoverItem, 0)
	for _, v := range list {
		item := &response.CommunityVideoCoverItem{
			CommunityVideoCoverId: v.CommunityVideoCoverId,
			CoverName:             v.CoverName,
			CoverUrl:              v.CoverUrl,
			CreateTime:            v.CreateTime.Format(utils.FormatDateTime),
			ModifyTime:            v.ModifyTime.Format(utils.FormatDateTime),
			Type:                  v.Type,
		}
		respList = append(respList, item)
	}
	resp.List = respList
	return
}

// SaveCommunityVideoCover 保存视频
func SaveCommunityVideoCover(coverId int, coverName, coverUrl string, coverType int8) (resp *response.CommunityVideoCoverItem, errMsg string, err error) {
	resp = new(response.CommunityVideoCoverItem)
	nowTime := time.Now().Local()
	// 更新
	if coverId > 0 {
		item, e := yb.GetCommunityVideoCoverById(coverId)
		if e != nil {
			errMsg = "封面信息有误"
			err = errors.New("获取封面图失败, Err:" + e.Error())
			return
		}
		updateCols := make([]string, 0)
		updateCols = append(updateCols, "CoverName", "CoverUrl", "ModifyTime", "type")
		item.CoverName = coverName
		item.CoverUrl = coverUrl
		item.ModifyTime = nowTime
		item.Type = coverType
		if e := item.Update(updateCols); e != nil {
			errMsg = "更新失败"
			err = errors.New("更新封面图失败, Err:" + e.Error())
		}
		resp = formatCommunityVideoCoverItem(item)
		return
	}
	// 新增
	newCover := &yb.CommunityVideoCover{
		CoverName:  coverName,
		CoverUrl:   coverUrl,
		CreateTime: nowTime,
		ModifyTime: nowTime,
		Type:       coverType,
	}
	if _, e := newCover.Add(); e != nil {
		errMsg = "新增失败"
		err = errors.New("新增封面图失败, Err:" + e.Error())
	}
	resp = formatCommunityVideoCoverItem(newCover)
	return
}

func formatCommunityVideoCoverItem(item *yb.CommunityVideoCover) (resp *response.CommunityVideoCoverItem) {
	resp = new(response.CommunityVideoCoverItem)
	if item != nil {
		resp.CommunityVideoCoverId = item.CommunityVideoCoverId
		resp.CoverName = item.CoverName
		resp.CoverUrl = item.CoverUrl
		resp.CreateTime = item.CreateTime.Format(utils.FormatDateTime)
		resp.ModifyTime = item.ModifyTime.Format(utils.FormatDateTime)
		resp.Type = item.Type
	}
	return
}

// SoftDeleteCommunityVideoCover 删除封面图
func SoftDeleteCommunityVideoCover(coverId int) (errMsg string, err error) {
	if _, e := yb.GetCommunityVideoCoverById(coverId); e != nil {
		errMsg = "封面图信息有误"
		err = errors.New("获取封面图失败, Err:" + e.Error())
		return
	}
	if e := yb.DeleteVideoCover(coverId); e != nil {
		errMsg = "删除失败"
		err = errors.New("删除封面图失败, Err:" + e.Error())
	}
	return
}
