package yb

import (
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/yb"
	"hongze/hz_crm_api/models/yb/response"
	"hongze/hz_crm_api/utils"
	"sync"
)

type ProductCensusController struct {
	controllers.BaseAuthController
}

// UserVisitCount
// @Title 用户阅读统计
// @Description 用户阅读统计
// @Param   UserId			query  int  true	"用户ID"
// @Param   ClickSort		query  int  false	"点击量排序：1-升序 2-降序"
// @Param   PageSize		query  int  false	"页码"
// @param   CurrentIndex	query  int  false	"每页数据量"
// @Success 200 {object}  response.ProductCensusUserVisitCountResp
// @router /product_census/user/visit_count [get]
func (this *ProductCensusController) UserVisitCount() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser is Empty"
		br.Ret = 408
		return
	}
	userId, _ := this.GetInt("UserId")
	if userId <= 0 {
		br.Msg = "参数有误"
		return
	}
	clickSort, _ := this.GetInt("ClickSort")
	orderRule := ``
	if clickSort == 1 {
		orderRule = `visit_count ASC`
	}
	if clickSort == 2 {
		orderRule = `visit_count DESC`
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	total, list, e := yb.GetProductVisitCountByUserId(userId, startSize, pageSize, orderRule)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取分产品阅读统计详情失败, Err: " + e.Error()
		return
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := response.ProductCensusUserVisitCountResp{
		List:   list,
		Paging: page,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
	return
}

// UserVisitCountDetail
// @Title 用户阅读统计详情
// @Description 用户阅读统计详情
// @Param   UserId			query  int  true	"用户ID"
// @Param   ProductType		query  int  true	"产品类型：1-语音播报 2-视频社区 3-问答社区 99-全部"
// @Param   ProductId		query  int  false	"产品ID：仅语音播报传该参数"
// @Param   ClickSort		query  int  false	"点击量排序：1-升序 2-降序"
// @Param   PageSize		query  int  false	"页码"
// @param   CurrentIndex	query  int  false	"每页数据量"
// @Success 200 {object}  ybResp.CommunityQuestionUserVisitCountResp
// @router /product_census/user/visit_count_detail [get]
func (this *ProductCensusController) UserVisitCountDetail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser is Empty"
		br.Ret = 408
		return
	}
	userId, _ := this.GetInt("UserId")
	if userId <= 0 {
		br.Msg = "参数有误"
		return
	}
	productType, _ := this.GetInt("ProductType")
	if productType <= 0 {
		br.Msg = "参数有误"
		return
	}
	productId, _ := this.GetInt("ProductId")
	if productType == 1 && productId <= 0 {
		br.Msg = "参数有误"
		return
	}
	clickSort, _ := this.GetInt("ClickSort")
	orderRule := ``
	if clickSort == 1 {
		orderRule = `visit_count ASC`
	}
	if clickSort == 2 {
		orderRule = `visit_count DESC`
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	total := 0
	respList := make([]*response.ProductCensusUserVisitCountDetail, 0)
	// 语音播报
	if productType == 1 {
		t, list, e := yb.GetVoiceBroadcastVisitCountByUserId(userId, productId, startSize, pageSize, orderRule)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取语音播报用户点击量统计失败, Err: " + e.Error()
			return
		}
		total = t

		for _, v := range list {
			respList = append(respList, &response.ProductCensusUserVisitCountDetail{
				VisitCount: v.VisitCount,
				Title:      v.BroadcastName,
				Source:     v.NewSource,
				RecentTime: v.RecentTime,
			})
		}
	}
	// 视频社区
	if productType == 2 {
		t, list, e := yb.GetCommunityVideoVisitCountByUserId(userId, productId, startSize, pageSize, orderRule)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取视频社区用户点击量统计失败, Err: " + e.Error()
			return
		}
		total = t
		// 视频标题
		videoIds := make([]int, 0)
		for _, v := range list {
			videoIds = append(videoIds, v.CommunityVideoId)
		}
		idTitleMap := make(map[int]string, 0)
		if productId == 1 {
			videoList, tErr := yb.GetCommunityVideoListByIds(videoIds)
			if tErr != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取视频社区列表失败, Err: " + tErr.Error()
				return
			}
			for _, v := range videoList {
				idTitleMap[v.CommunityVideoId] = v.Title
			}
		} else {
			videoList, tErr := yb.GetRoadVideoListByIds(videoIds)
			if tErr != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取视频社区列表失败, Err: " + tErr.Error()
				return
			}
			for _, v := range videoList {
				idTitleMap[v.RoadVideoId] = v.Title
			}
		}

		for _, v := range list {
			respList = append(respList, &response.ProductCensusUserVisitCountDetail{
				VisitCount: v.VisitCount,
				Title:      idTitleMap[v.CommunityVideoId],
				Source:     v.NewSource,
				RecentTime: v.RecentTime,
			})
		}
	}

	// 问答社区
	if productType == 3 {
		t, list, e := yb.GetCommunityQuestionVisitCountByUserId(userId, startSize, pageSize, orderRule)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取问答社区用户点击量统计失败, Err: " + e.Error()
			return
		}
		total = t
		// 问题内容
		questionIds := make([]int, 0)
		for _, v := range list {
			questionIds = append(questionIds, v.CommunityQuestionId)
		}
		questionList, e := yb.GetQuestionListByIds(questionIds)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取问答列表失败, Err: " + e.Error()
			return
		}
		idTitleMap := make(map[int]string, 0)
		for _, v := range questionList {
			idTitleMap[v.CommunityQuestionId] = v.QuestionContent
		}

		for _, v := range list {
			respList = append(respList, &response.ProductCensusUserVisitCountDetail{
				VisitCount: v.VisitCount,
				Title:      idTitleMap[v.CommunityQuestionId],
				Source:     v.NewSource,
				RecentTime: v.RecentTime,
			})
		}
	}

	// 全部
	if productType == 99 {
		listTotal, list, e := yb.GetUserAllYbProductVisitCountPageList(userId, startSize, pageSize, orderRule)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取用户所有产品点击量失败, Err: " + e.Error()
			return
		}
		total = listTotal

		sectionIds := make([]int, 0)
		videoIds := make([]int, 0)
		rsVideoIds := make([]int, 0)
		questionIds := make([]int, 0)

		for _, v := range list {
			// 语音播报-取出板块ID
			if v.ProductType == 1 && v.SectionId > 0 && !utils.InArrayByInt(sectionIds, v.SectionId) {
				sectionIds = append(sectionIds, v.SectionId)
			}
			// 视频社区-取出视频ID
			if v.ProductType == 2 && v.TitleId > 0 {
				if v.VideoType == 1 && !utils.InArrayByInt(videoIds, v.TitleId) {
					videoIds = append(videoIds, v.TitleId)
				}
				if v.VideoType == 2 && !utils.InArrayByInt(rsVideoIds, v.TitleId) {
					rsVideoIds = append(rsVideoIds, v.TitleId)
				}
			}
			// 问答社区-取出问题ID
			if v.ProductType == 3 && v.TitleId > 0 && !utils.InArrayByInt(questionIds, v.TitleId) {
				questionIds = append(questionIds, v.TitleId)
			}
		}

		var sectionErr, videoErr, questionErr error
		wg := sync.WaitGroup{}
		wg.Add(3)

		// 板块名称map
		sectionNameMap := make(map[int]string, 0)
		go func() {
			defer func() {
				wg.Done()
			}()

			sectionList, e := yb.GetVoiceSectionByIds(sectionIds)
			if e != nil {
				sectionErr = fmt.Errorf("获取语音播报板块列表失败, Err: %s", e.Error())
				return
			}
			for _, v := range sectionList {
				sectionNameMap[v.SectionId] = v.SectionName
			}
		}()

		// 视频社区标题map
		videoTitleMap := make(map[int]string, 0)
		rsVideoTitleMap := make(map[int]string, 0)
		go func() {
			defer func() {
				wg.Done()
			}()

			videoList, e := yb.GetCommunityVideoListByIds(videoIds)
			if e != nil {
				videoErr = fmt.Errorf("获取视频社区列表失败, Err: %s", e.Error())
				return
			}
			for _, v := range videoList {
				videoTitleMap[v.CommunityVideoId] = v.Title
			}

			rsVideoList, e := yb.GetRoadVideoListByIds(rsVideoIds)
			if e != nil {
				videoErr = fmt.Errorf("获取路演视频列表失败, Err: %s", e.Error())
				return
			}
			for _, v := range rsVideoList {
				rsVideoTitleMap[v.RoadVideoId] = v.Title
			}
		}()

		// 问答社区标题map
		questionTitleMap := make(map[int]string, 0)
		go func() {
			defer func() {
				wg.Done()
			}()

			questionList, e := yb.GetQuestionListByIds(questionIds)
			if e != nil {
				questionErr = fmt.Errorf("获取问答列表失败, Err: %s", e.Error())
				return
			}
			for _, v := range questionList {
				questionTitleMap[v.CommunityQuestionId] = v.QuestionContent
			}
		}()

		wg.Wait()
		if sectionErr != nil {
			br.Msg = "获取失败"
			br.ErrMsg = sectionErr.Error()
			return
		}
		if videoErr != nil {
			br.Msg = "获取失败"
			br.ErrMsg = videoErr.Error()
			return
		}
		if questionErr != nil {
			br.Msg = "获取失败"
			br.ErrMsg = questionErr.Error()
			return
		}

		// 填充产品名/标题
		for _, v := range list {
			d := new(response.ProductCensusUserVisitCountDetail)
			d.VisitCount = v.VisitCount
			d.Source = v.NewSource
			d.RecentTime = v.RecentTime
			if v.ProductType == 1 {
				d.ProductName = sectionNameMap[v.SectionId]
				d.Title = v.Title
			}
			if v.ProductType == 2 {
				if v.VideoType == 1 {
					d.ProductName = "5分钟小视频"
					d.Title = videoTitleMap[v.TitleId]
				}
				if v.VideoType == 2 {
					d.ProductName = "线上路演"
					d.Title = rsVideoTitleMap[v.TitleId]
				}
			}
			if v.ProductType == 3 {
				d.ProductName = "问答社区"
				d.Title = questionTitleMap[v.TitleId]
			}

			respList = append(respList, d)
		}
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := response.ProductCensusUserVisitCountDetailResp{
		List:   respList,
		Paging: page,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
	return
}
