package media

import (
	logger "eta/eta_mini_ht_api/common/component/log"
	"eta/eta_mini_ht_api/common/exception"
	"eta/eta_mini_ht_api/common/utils/page"
	stringUtils "eta/eta_mini_ht_api/common/utils/string"
	mediaService "eta/eta_mini_ht_api/domian/media"
	userService "eta/eta_mini_ht_api/domian/user"
	"eta/eta_mini_ht_api/models/user"
	"strings"
	"sync"
)

const (
	video = "video"
	audio = "audio"
)

type RecordCount struct {
	UserId     int
	Mobile     string
	MediaId    int
	MediaType  string
	IpAddress  string
	Location   string
	Referer    string
	Additional string
}

func convertToMediaCountDTO(record RecordCount, sourceType user.SourceType) (dto userService.RecordCountDTO) {
	return userService.RecordCountDTO{
		UserId:     record.UserId,
		Mobile:     record.Mobile,
		SourceId:   record.MediaId,
		SourceType: sourceType,
	}
}
func getSourceType(mediaType string) user.SourceType {
	switch mediaType {
	case video:
		return user.VideoSourceType
	case audio:
		return user.AudioSourceType
	default:
		return ""
	}
}
func CountMedia(count RecordCount) (err error) {
	media, err := mediaService.GetMediaById(count.MediaType, count.MediaId)
	sourceType := getSourceType(media.MediaType)
	if sourceType == "" {
		err = exception.New(exception.MediaTypeError)
		return
	}
	dto := convertToMediaCountDTO(count, sourceType)
	return userService.CountMedia(dto)
}
func GetTotalPageCount(mediaType string) (count int64, latestId int64) {
	if mediaType == "" {
		return
	}
	return mediaService.GetTotalPageCount(mediaType)
}
func GetTotalPageCountByAnalystId(mediaType string, analystId int) (total int64, latestId int64) {
	if mediaType == "" {
		return
	}
	return mediaService.GetTotalPageCountByAnalystId(mediaType, analystId)
}
func GetTotalPageCountByPermissionIds(mediaType string, permissionIds []int) (total int64, latestId int64, ids []int) {
	if mediaType == "" {
		return
	}
	if len(permissionIds) == 0 {
		total, latestId = mediaService.GetTotalPageCount(mediaType)
		ids = []int{}
		return
	}
	return mediaService.GetMediaPermissionMappingByPermissionIds(mediaType, permissionIds)
}
func SearchMaxMediaId(mediaType string, key string) (total int64, latestId int64) {
	return mediaService.SearchMaxMediaId(mediaType, key)
}
func GetMediaById(mediaType string, mediaId int) (media mediaService.MediaDTO, err error) {
	media, err = mediaService.GetMediaById(mediaType, mediaId)
	if err != nil {
		err = exception.New(exception.MediaFoundFailed)
	}
	idStr := strings.Split(media.PermissionIDs, ",")
	var ids []int
	ids, err = stringUtils.StringToIntSlice(idStr)
	if err != nil {
		logger.Error("品种名称列表转换失败:%v", err)
	}
	media.PermissionNames = getMediaPermissionNames(ids)
	return
}

func GetMediaPageByAnalystId(mediaType string, pageInfo page.PageInfo, analystId int) (list []mediaService.MediaDTO, err error) {
	list, err = mediaService.GetMediaPageByAnalystId(mediaType, pageInfo, analystId)
	if err != nil {
		err = exception.New(exception.GetAnalystMediaListFailed)
		return
	}
	//并发获取媒体的标签
	var wg sync.WaitGroup
	wg.Add(len(list))
	for i := 0; i < len(list); i++ {
		go func(media *mediaService.MediaDTO) {
			defer wg.Done()
			idStr := strings.Split(media.PermissionIDs, ",")
			var ids []int
			ids, err = stringUtils.StringToIntSlice(idStr)
			if err != nil {
				logger.Error("品种名称列表转换失败:%v", err)
			}
			media.PermissionNames = getMediaPermissionNames(ids)
		}(&list[i])
	}
	wg.Wait()
	if err != nil {
		err = exception.New(exception.QueryReportPageFailed)
	}
	return
}

func GetMediaPageByIds(mediaType string, pageInfo page.PageInfo, mediaIds []int) (list []mediaService.MediaDTO, err error) {
	list, err = mediaService.GetMediaPageByIds(mediaType, pageInfo, mediaIds)
	if err != nil {
		err = exception.New(exception.GetMediaListFailed)
		return
	}
	//并发获取媒体的标签
	var wg sync.WaitGroup
	wg.Add(len(list))
	for i := 0; i < len(list); i++ {
		go func(media *mediaService.MediaDTO) {
			defer wg.Done()
			idStr := strings.Split(media.PermissionIDs, ",")
			var ids []int
			ids, err = stringUtils.StringToIntSlice(idStr)
			if err != nil {
				logger.Error("品种名称列表转换失败:%v", err)
			}
			media.PermissionNames = getMediaPermissionNames(ids)
		}(&list[i])
	}
	wg.Wait()
	if err != nil {
		err = exception.New(exception.QueryReportPageFailed)
	}
	return
}
func getMediaPermissionNames(id []int) (labels []string) {
	permissions, err := mediaService.GetPermissionsByIds(id)
	if err != nil {
		logger.Error("查询品种名称列表失败:%v", err)
		labels = []string{}
		return
	}
	for _, permission := range permissions {
		labels = append(labels, permission.Name)
	}
	return
}

// stringToIntSlice 将一个包含数字字符串的切片转换为整数切片

func SearchMediaList(mediaType string, key string, pageInfo page.PageInfo) (medias []mediaService.MediaDTO, err error) {
	offset := page.StartIndex(pageInfo.Current, pageInfo.PageSize)
	medias, err = mediaService.SearchMediaList(mediaType, key, offset, pageInfo.PageSize, pageInfo.LatestId)
	var wg sync.WaitGroup
	wg.Add(len(medias))
	for i := 0; i < len(medias); i++ {
		go func(media *mediaService.MediaDTO) {
			defer wg.Done()
			idStr := strings.Split(media.PermissionIDs, ",")
			var ids []int
			ids, err = stringUtils.StringToIntSlice(idStr)
			if err != nil {
				logger.Error("获取品种列表失败:%v", err)
			}
			media.PermissionNames = getMediaPermissionNames(ids)
		}(&medias[i])
	}
	wg.Wait()
	if err != nil {
		err = exception.New(exception.SearchReportPageFailed)
	}
	return
}
