package community

import (
	"errors"
	response2 "hongze/hongze_yb/controller/response"
	"hongze/hongze_yb/models/response"
	"hongze/hongze_yb/models/tables/company_product"
	"hongze/hongze_yb/models/tables/rddp/chart_permission"
	"hongze/hongze_yb/models/tables/yb_community_question_comment"
	"hongze/hongze_yb/models/tables/yb_community_question_like_tease"
	"hongze/hongze_yb/models/tables/yb_community_video"
	"hongze/hongze_yb/models/tables/yb_community_video_play_log"
	"hongze/hongze_yb/models/tables/yb_road_video"
	"hongze/hongze_yb/services/collection"
	"hongze/hongze_yb/services/company"
	"hongze/hongze_yb/services/user"
	"hongze/hongze_yb/utils"
	"strconv"
	"strings"
	"time"
)

// GetVideoList 获取视频列表
func GetVideoList(userId, 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
	}
	videoIds := make([]int, 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,
			PublishTime:         v.PublishTime.Format(utils.FormatDateTime),
			CreateTime:          v.CreateTime.Format(utils.FormatDateTime),
			ModifyTime:          v.ModifyTime.Format(utils.FormatDateTime),
			ChartPermissionName: v.VarietyTagName,
			TencentId:           getSubTencentUrl(v.TencentURL),
		}
		resp = append(resp, item)
		videoIds = append(videoIds, v.CommunityVideoID)
	}

	// 收藏
	collectMap, e := collection.GetUserCollectByList(userId, collection.CollectionTypeVideo, videoIds)
	if e != nil {
		err = e
		return
	}
	for i := range resp {
		resp[i].CollectionId = collectMap[resp[i].CommunityVideoID]
	}
	return
}

// SaveVideoPlayLog 记录用户播放视频日志
func SaveVideoPlayLog(userInfo user.UserInfo, videoId, sourceAgent int, videoType int8) (newId int, errMsg string, err error) {
	if videoType == 1 {
		_, e := yb_community_video.GetItemById(videoId)
		if e != nil {
			errMsg = "视频不存在或未发布"
			err = errors.New("获取视频信息失败, Err: " + e.Error())
			return
		}
	} else {
		_, e := yb_road_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 := "潜在"
	sellerId := 0
	if companyInfo != nil {
		if companyInfo.CompanyID > 0 {
			companyName = companyInfo.CompanyName
			companyStatus = companyInfo.Status
		}
		sellerId = companyInfo.SellerID
	}

	item := &yb_community_video_play_log.YbCommunityVideoPlayLog{
		CommunityVideoID: videoId,
		UserID:           int(userInfo.UserID),
		Mobile:           userInfo.Mobile,
		RealName:         userInfo.RealName,
		NickName:         userInfo.NickName,
		CompanyID:        int(userInfo.CompanyID),
		CompanyName:      companyName,
		CompanyStatus:    companyStatus,
		SourceAgent:      sourceAgent,
		SellerID:         sellerId,
		Type:             videoType,
		CreateTime:       time.Now().Local(),
	}
	if e = item.Create(); e != nil {
		errMsg = "操作失败"
		err = errors.New("新增播放视频日志失败, Err:" + e.Error())
		return
	}
	newId = item.ID
	return
}

// getSubTencentUrl 获取腾讯视频链接子字符串
func getSubTencentUrl(tencentUrl string) (sub string) {
	if tencentUrl != "" {
		st := strings.LastIndex(tencentUrl, "/")
		ed := strings.LastIndex(tencentUrl, ".")
		if st > 0 && ed > st {
			sub = tencentUrl[st+1 : ed]
		}
	}
	return
}

// GetRoadVideoList 获取线上路演视频列表
func GetRoadVideoList(userInfo user.UserInfo, pageIndex, pageSize, videoId, chartPermissionId int, keywords string) (resp response.RoadVideoItemResp, err error, code int) {
	list := make([]*response.RoadVideoItem, 0)
	//获取有权限的permissionID
	validPermissionList, err := company.GetValidPermissionByCompany2ProductId(userInfo.CompanyID, 1)
	if err != nil {
		return
	}

	ficcPermissionList, err := chart_permission.GetFiccListExceptTacticByProductId()
	if err != nil {
		return
	}
	permissionIds := ""
	validPermissionMap := make(map[string]struct{})
	ParentPermissionNameMap := make(map[string]string)
	ParentPermissionChildMap := make(map[string]int)
	for _, v := range validPermissionList {
		permissionIds += "'" + strconv.Itoa(v.ChartPermissionID) + "'|"
		validPermissionMap["'"+strconv.Itoa(v.ChartPermissionID)+"'"] = struct{}{}
	}
	for _, v := range ficcPermissionList {
		ParentPermissionNameMap["'"+strconv.Itoa(int(v.ChartPermissionID))+"'"] = v.ClassifyName
		ParentPermissionChildMap[v.ClassifyName] += 1
	}

	if permissionIds == "" {
		resp.List = list
		resp.Paging = response.GetPaging(pageIndex, pageSize, 0)
		return
	}
	permissionIds = strings.Trim(permissionIds, "|")
	condition := `is_deleted = 0 AND publish_state = 1 and chart_permission_ids REGEXP "(` + permissionIds + `)"`
	var par []interface{}
	// 分享点进来的直接定位到具体视频
	var videoList []*yb_road_video.YbRoadVideo
	var total int64
	if videoId > 0 {
		videoInfo, e := yb_road_video.GetItemById(videoId)
		if e != nil {
			if e != utils.ErrNoRow {
				err = errors.New("获取视频信息失败, Err:" + e.Error())
				return
			}
		}
		if videoInfo != nil && videoInfo.RoadVideoID > 0 {
			if videoInfo.IsDeleted != 0 || videoInfo.PublishState != 1 {
				resp.List = list
				resp.Paging = response.GetPaging(pageIndex, pageSize, 0)
				return
			}
			permissionIdsSlice := strings.Split(permissionIds, "|")
			videoPermissionIdsSlice := strings.Split(videoInfo.ChartPermissionIds, ",")
			hasPermission := false
			for _, v1 := range permissionIdsSlice {
				for _, v2 := range videoPermissionIdsSlice {
					if v1 == v2 {
						hasPermission = true
						break
					}
				}
			}

			if !hasPermission { //无权限
				code = response2.SPECIFIC_FAIL_CODE
				err = errors.New("无查看该视频的权限")
				return
			}
			videoList = append(videoList, videoInfo)
			total = 1
		}
	} else {
		if chartPermissionId > 0 {
			condition += ` and FIND_IN_SET("'` + strconv.Itoa(chartPermissionId) + `'", chart_permission_ids)`
		}
		if keywords != "" {
			condition += " and title like ? "
			par = append(par, "%"+keywords+"%")
		}
		videoList, total, err = yb_road_video.GetPageListByCondition(condition, par, pageIndex, pageSize)
		if err != nil {
			err = errors.New("获取视频列表失败, Err:" + err.Error())
			return
		}
	}

	if len(videoList) <= 0 {
		resp.List = list
		resp.Paging = response.GetPaging(pageIndex, pageSize, 0)
		return
	}

	chartPermissionIdSlice := make([]int, 0)
	chartNameMap := make(map[string]string)

	for _, v := range videoList {
		tmp := strings.Split(v.ChartPermissionIds, ",")
		for _, t1 := range tmp {
			i, _ := strconv.Atoi(strings.Trim(t1, "'"))
			chartPermissionIdSlice = append(chartPermissionIdSlice, i)
		}
	}
	if len(chartPermissionIdSlice) > 0 {
		chartList, e := chart_permission.GetListByIds(chartPermissionIdSlice)
		if e != nil {
			err = errors.New("获取品种信息失败, Err:" + e.Error())
			return
		}
		for _, v := range chartList {
			chartNameMap["'"+strconv.Itoa(int(v.ChartPermissionID))+"'"] = v.PermissionName
		}
	}
	var chartPermissionNames string

	videoIds := make([]int, 0)
	for _, v := range videoList {
		chartPermissionNames = ""
		itemParentPermissionNum := make(map[string]int)
		tmpSlice := strings.Split(v.ChartPermissionIds, ",")
		if len(tmpSlice) > 0 {
			// 拼接一级标签
			for _, cid := range tmpSlice {
				if p, ok := ParentPermissionNameMap[cid]; ok {
					if _, ok1 := itemParentPermissionNum[p]; !ok1 {
						itemParentPermissionNum[p] = 0
						chartPermissionNames += p + ","
					}
				}
			}
			// 查询可显示的所有品种是否包含所有一级品种的二级品种
			for _, cid := range tmpSlice {
				if _, ok := chartNameMap[cid]; ok {
					if _, ok1 := validPermissionMap[cid]; ok1 {
						itemParentPermissionNum[ParentPermissionNameMap[cid]] += 1
					}
				}
			}
			for _, cid := range tmpSlice {
				if n, ok := ParentPermissionChildMap[ParentPermissionNameMap[cid]]; ok && n != itemParentPermissionNum[ParentPermissionNameMap[cid]] {
					chartPermissionNames = ""
					break
				}
			}

			if chartPermissionNames == "" {
				for _, cid := range tmpSlice {
					if name, ok := chartNameMap[cid]; ok {
						if _, ok1 := validPermissionMap[cid]; ok1 {
							chartPermissionNames += name + ","
						}
					}
				}
			}

			if chartPermissionNames != "" {
				chartPermissionNames = strings.Trim(chartPermissionNames, ",")
			}
		}

		item := &response.RoadVideoItem{
			RoadVideoID:         v.RoadVideoID,
			Title:               v.Title,
			ChartPermissionIds:  v.ChartPermissionIds,
			ChartPermissionName: chartPermissionNames,
			CoverImgUrl:         v.CoverImgURL,
			VideoUrl:            v.VideoURL,
			VideoSeconds:        v.VideoSeconds,
			PublishState:        v.PublishState,
			AdminId:             v.AdminId,
			AdminRealName:       v.AdminRealName,
			PublishTime:         v.PublishTime.Format(utils.FormatDateTime),
			CreateTime:          v.CreateTime.Format(utils.FormatDateTime),
			ModifyTime:          v.ModifyTime.Format(utils.FormatDateTime),
			ReportId:            v.ReportID,
		}
		list = append(list, item)
		videoIds = append(videoIds, item.RoadVideoID)
	}

	// 收藏
	collectMap, e := collection.GetUserCollectByList(int(userInfo.UserID), collection.CollectionTypeRoadVideo, videoIds)
	if e != nil {
		err = e
		return
	}
	for i := range list {
		list[i].CollectionId = collectMap[list[i].RoadVideoID]
	}

	resp.List = list
	resp.Paging = response.GetPaging(pageIndex, pageSize, int(total))
	return
}

// HandleLikeOrTeaseByCommunityVideoItemList 视频社区 点赞/吐槽 数据
func HandleLikeOrTeaseByCommunityVideoItemList(userId uint64, videoList []*response.CommunityVideoItem) (err error) {
	listLen := len(videoList)
	if listLen == 0 {
		return
	}
	idArr := make([]uint32, 0)
	for i := 0; i < listLen; i++ {
		idArr = append(idArr, uint32(videoList[i].CommunityVideoID))
	}

	// 注:此处视频社区CommunityVideoID在点赞吐槽表中为CommunityQuestionID, 以source区分主键

	// 获取点赞和吐槽数据
	ybCommunityQuestionLikeTeaseMap := make(map[uint32]*yb_community_question_like_tease.YbCommunityQuestionLikeTease)
	ybCommunityQuestionLikeTeaseList, err := yb_community_question_like_tease.GetByUserIdAndCommunityQuestionIds(userId, idArr, yb_community_question_like_tease.SourceVideo)
	if err != nil {
		return
	}
	for _, v := range ybCommunityQuestionLikeTeaseList {
		ybCommunityQuestionLikeTeaseMap[v.CommunityQuestionID] = v
	}

	// 获取点赞和吐槽汇总数
	likeMap := make(map[uint32]int)
	teaseMap := make(map[uint32]int)

	likeList, err := yb_community_question_like_tease.GetLikeNumCommentByCommunityQuestionIds(idArr, yb_community_question_like_tease.SourceVideo)
	if err != nil {
		return
	}
	for _, v := range likeList {
		likeMap[v.CommunityQuestionID] = v.Total
	}

	teaseList, err := yb_community_question_like_tease.GetTeaseNumCommentByCommunityQuestionIds(idArr, yb_community_question_like_tease.SourceVideo)
	if err != nil {
		return
	}
	for _, v := range teaseList {
		teaseMap[v.CommunityQuestionID] = v.Total
	}

	for _, v := range videoList {
		if tmpTotal, ok := likeMap[uint32(v.CommunityVideoID)]; ok {
			v.LikeTotal = tmpTotal
		}
		if tmpTotal, ok := teaseMap[uint32(v.CommunityVideoID)]; ok {
			v.TeaseTotal = tmpTotal
		}

		if ybCommunityQuestionLikeTease, ok := ybCommunityQuestionLikeTeaseMap[uint32(v.CommunityVideoID)]; ok {
			//类型. 1-点赞 2-吐槽
			v.OpType = ybCommunityQuestionLikeTease.OpType
		}
	}
	return
}

// HandleCommentByCommunityVideoItemList 视频 评论 数据
func HandleCommentByCommunityVideoItemList(questionList []*response.CommunityVideoItem) (err error) {
	listLen := len(questionList)
	if listLen == 0 {
		return
	}
	idArr := make([]uint32, 0)

	// 注:此处视频社区CommunityVideoID在评论表中为CommunityQuestionID, 以source区分主键

	// 问题ID-精选评论列表
	questionIdCommentsMap := make(map[uint32][]*response.CommunityQuestionCommentListItem, 0)

	for i := 0; i < listLen; i++ {
		idArr = append(idArr, uint32(questionList[i].CommunityVideoID))
		questionIdCommentsMap[uint32(questionList[i].CommunityVideoID)] = make([]*response.CommunityQuestionCommentListItem, 0)
	}

	// 精选评论数据
	hotList, err := yb_community_question_comment.GetHotListByCommunityQuestionIds(idArr, yb_community_question_comment.SourceVideo)
	if err != nil {
		return
	}
	for _, v := range hotList {
		questionIdCommentsMap[v.CommunityQuestionID] = append(questionIdCommentsMap[v.CommunityQuestionID], &response.CommunityQuestionCommentListItem{
			QaAvatarUrl: v.QaAvatarUrl,
			Comment:     v.Content,
		})
	}

	for _, v := range questionList {
		comments := questionIdCommentsMap[uint32(v.CommunityVideoID)]
		v.CommentTotal = len(comments)
		v.CommentList = comments
	}

	return
}

// HandleLikeOrTeaseByRoadVideoItemList 路演视频 点赞/吐槽 数据
func HandleLikeOrTeaseByRoadVideoItemList(userId uint64, videoList []*response.RoadVideoItem) (err error) {
	listLen := len(videoList)
	if listLen == 0 {
		return
	}
	idArr := make([]uint32, 0)
	for i := 0; i < listLen; i++ {
		idArr = append(idArr, uint32(videoList[i].RoadVideoID))
	}

	// 注:此处视频社区CommunityVideoID在点赞吐槽表中为CommunityQuestionID, 以source区分主键

	// 获取点赞和吐槽数据
	ybCommunityQuestionLikeTeaseMap := make(map[uint32]*yb_community_question_like_tease.YbCommunityQuestionLikeTease)
	ybCommunityQuestionLikeTeaseList, err := yb_community_question_like_tease.GetByUserIdAndCommunityQuestionIds(userId, idArr, yb_community_question_like_tease.SourceRoadVideo)
	if err != nil {
		return
	}
	for _, v := range ybCommunityQuestionLikeTeaseList {
		ybCommunityQuestionLikeTeaseMap[v.CommunityQuestionID] = v
	}

	// 获取点赞和吐槽汇总数
	likeMap := make(map[uint32]int)
	teaseMap := make(map[uint32]int)

	likeList, err := yb_community_question_like_tease.GetLikeNumCommentByCommunityQuestionIds(idArr, yb_community_question_like_tease.SourceRoadVideo)
	if err != nil {
		return
	}
	for _, v := range likeList {
		likeMap[v.CommunityQuestionID] = v.Total
	}

	teaseList, err := yb_community_question_like_tease.GetTeaseNumCommentByCommunityQuestionIds(idArr, yb_community_question_like_tease.SourceRoadVideo)
	if err != nil {
		return
	}
	for _, v := range teaseList {
		teaseMap[v.CommunityQuestionID] = v.Total
	}

	for _, v := range videoList {
		if tmpTotal, ok := likeMap[uint32(v.RoadVideoID)]; ok {
			v.LikeTotal = tmpTotal
		}
		if tmpTotal, ok := teaseMap[uint32(v.RoadVideoID)]; ok {
			v.TeaseTotal = tmpTotal
		}

		if ybCommunityQuestionLikeTease, ok := ybCommunityQuestionLikeTeaseMap[uint32(v.RoadVideoID)]; ok {
			//类型. 1-点赞 2-吐槽
			v.OpType = ybCommunityQuestionLikeTease.OpType
		}
	}
	return
}

// HandleCommentByRoadVideoItemList 路演视频 -论数据
func HandleCommentByRoadVideoItemList(questionList []*response.RoadVideoItem) (err error) {
	listLen := len(questionList)
	if listLen == 0 {
		return
	}
	idArr := make([]uint32, 0)

	// 注:此处视频社区RoadVideoID在评论表中为CommunityQuestionID, 以source区分主键

	// 问题ID-精选评论列表
	questionIdCommentsMap := make(map[uint32][]*response.CommunityQuestionCommentListItem, 0)

	for i := 0; i < listLen; i++ {
		idArr = append(idArr, uint32(questionList[i].RoadVideoID))
		questionIdCommentsMap[uint32(questionList[i].RoadVideoID)] = make([]*response.CommunityQuestionCommentListItem, 0)
	}

	// 精选评论数据
	hotList, err := yb_community_question_comment.GetHotListByCommunityQuestionIds(idArr, yb_community_question_comment.SourceRoadVideo)
	if err != nil {
		return
	}
	for _, v := range hotList {
		questionIdCommentsMap[v.CommunityQuestionID] = append(questionIdCommentsMap[v.CommunityQuestionID], &response.CommunityQuestionCommentListItem{
			QaAvatarUrl: v.QaAvatarUrl,
			Comment:     v.Content,
		})
	}

	for _, v := range questionList {
		comments := questionIdCommentsMap[uint32(v.RoadVideoID)]
		v.CommentTotal = len(comments)
		v.CommentList = comments
	}
	return
}