package report

import (
	"errors"
	"fmt"
	report_chapter_type_cache "hongze/hongze_yb/cache/report_chapter_type"
	"hongze/hongze_yb/global"
	"hongze/hongze_yb/models/response"
	"hongze/hongze_yb/models/tables/chart_permission_chapter_mapping"
	"hongze/hongze_yb/models/tables/company_product"
	"hongze/hongze_yb/models/tables/rddp/classify"
	"hongze/hongze_yb/models/tables/rddp/report"
	"hongze/hongze_yb/models/tables/rddp/report_chapter"
	"hongze/hongze_yb/models/tables/report_chapter_type"
	"hongze/hongze_yb/services"
	"hongze/hongze_yb/services/company"
	"hongze/hongze_yb/services/user"
	"hongze/hongze_yb/utils"
	"html"
	"sort"
	"strings"
	"time"
)

// GetReportTypeIdsByPermissionIds 获取所有和权限绑定的报告章节ID
func GetReportTypeIdsByPermissionIds(permissionIds []int) (ids []int, err error)   {
	ids, err = chart_permission_chapter_mapping.GetReportIdsByPermisssionIds(permissionIds, "week")
	return
}

// GetLatestWeek 获取有权限的最新的周报
func GetLatestWeek(permissionIds []int, typeIds []int) (reportInfo *report.Report, err error) {
	newTypeIds, err := GetWeekTypeIdsByPermissionIds(permissionIds, typeIds)
	chapters, err := report_chapter.GetLatestChaptersByTypeIdsAndClass(newTypeIds,"week")
	if err != nil {
		return
	}
	var reportIds []int
	for _, v := range chapters {
		reportIds = append(reportIds, v.ReportId)
	}
	reportInfo, err = report.GetLatestByReportIds(reportIds)
	return
}

// GetWeekTypeIdsByPermissionIds 获取有权限的章节类型ID
func GetWeekTypeIdsByPermissionIds(permissionIds []int, typeIds []int) (newTypeIds []int, err error)  {
	ids, err := GetReportTypeIdsByPermissionIds(permissionIds)
	if err != nil {
		return
	}
	if len(typeIds) == 0 {
		typeIds, err = report_chapter_type_cache.GetEffectTypeID()
		if err != nil {
			return
		}
	}
	for _, v1 := range typeIds {
		for _, v2 := range ids {
			if v1 == v2 {
				newTypeIds = append(newTypeIds, v2)
			}
		}
	}
	return
}

// GetChapterListByReport 根据报告获取章节列表
func GetChapterListByReport(classifyNameFirst string, reportId int, validWeekTypeIds []int, reportCreateTime time.Time) (reportTypeList response.ReportChapterList, err error) {
	var errMsg string
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("GetChapterListByReport: err:%s， errMsg:%s", err.Error(), errMsg))
		}
	}()
	//查询有效的章节
	typeList, tErr := report_chapter_type.GetEffectTypes()
	if tErr != nil {
		errMsg = tErr.Error()
		err = errors.New("章节类型查询出错")
		return
	}
	if len(typeList) == 0 {
		err = errors.New("无有效的章节")
		return
	}

	typeMap := make(map[uint64]*report_chapter_type.ReportChapterType)
	var typeIds []int
	newTypeMap := make(map[int]bool)
	for _, v := range typeList {
		typeMap[v.ReportChapterTypeId] = v
		typeIds = append(typeIds, int(v.ReportChapterTypeId))
	}

	if classifyNameFirst == "周报" {
		for _, v := range validWeekTypeIds {
			newTypeMap[v] = true
		}
	}
	//获取所有当前研报的章节
	chapterList, tErr := report_chapter.GetListByReportId(reportId, classifyNameFirst)
	if tErr != nil && tErr != utils.ErrNoRow{
		errMsg = err.Error()
		err = errors.New("章节查询出错")
		return
	}
	if len(chapterList) == 0 {
		err = errors.New("无有效章节")
		return
	}

	for _, item := range chapterList {
		if typeItem, ok := typeMap[uint64(item.TypeId)]; ok {
			// 如果是周报只展示有权限的章节
			if  classifyNameFirst == "周报" {
				if _, ok1 := newTypeMap[item.TypeId]; !ok1 {
					continue
				}
			}
			temp := new(response.ReportChapterListItem)
			if reportCreateTime.Before(typeItem.PauseStartTime) || reportCreateTime.After(typeItem.PauseEndTime) {
				temp.ReportChapterId = item.ReportChapterId
				temp.TypeId = item.TypeId
				temp.TypeName = item.TypeName
				temp.Title = item.Title
				temp.Trend = item.Trend
				temp.ReportId = item.ReportId
				temp.Sort = typeItem.Sort
				temp.PublishTime = item.PublishTime
				temp.ReportChapterTypeKey = typeItem.ReportChapterTypeKey
				temp.ReportChapterTypeName = typeItem.ReportChapterTypeName
				temp.ReportChapterTypeThumb = typeItem.YbIconUrl
				reportTypeList = append(reportTypeList, temp)
			}
		}
	}
	if len(reportTypeList) > 0 {
		sort.Sort(reportTypeList)
	}
	return
}

// GetChapterDetail 获取章节详情
func GetChapterDetail(user user.UserInfo, reportChapterId int) (reportChapterDetail *response.ReportChapterDetail, err error) {
	var errMsg string
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("GetChapterDetail: userId=%d, err:%s， errMsg:%s", user.UserID, err.Error(), errMsg))
		}
	}()

	var authOk bool
	var productAuthOk bool
	var chapterAuthOk bool
	var permissionCheckInfo response.PermissionCheckInfo
	// 判断用户状态是否是正常和永续
	companyProduct, err := company_product.GetByCompany2ProductId(user.CompanyID, 1)
	if err == utils.ErrNoRow {
		err = nil
	}
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询用户购买产品出错")
		return
	}
	if companyProduct != nil {
		// 无FICC权限的客户不可见
		if companyProduct.CompanyProductID > 0 {
			// 已购或者试用用户可见
			if strings.Contains("永续,正式", companyProduct.Status) || (companyProduct.Status == "试用" && companyProduct.IsSuspend != 1) {
				productAuthOk = true
			}
		}
	}

	typeIds, err := report_chapter_type_cache.GetEffectTypeID()
	if err != nil {
		errMsg = err.Error()
		err = errors.New("章节类型查询出错")
		return
	}
	if len(typeIds) == 0 {
		err = errors.New("无有效的章节类型")
		return
	}
	reportChapter, err := report_chapter.GetContentById(reportChapterId, typeIds)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("章节查询出错")
		return
	}

	if reportChapter.ReportChapterId == 0 {
		err = errors.New("章节不存在")
		return
	}

	reportInfo, tErr := report.GetByReportId(reportChapter.ReportId)
	if tErr != nil {
		errMsg = tErr.Error()
		err = errors.New("报告查询出错")
		return
	}
	if reportInfo.Id == 0 {
		err = errors.New("报告不存在")
		return
	}
	if reportInfo.ClassifyNameFirst == "周报" && reportChapter.IsEdit != 1 {
		err = errors.New("章节未编辑")
		return
	}
	//判断权限
	var newTypeIds []int
	if reportInfo.ClassifyNameFirst == "晨报"{
		authOk, permissionCheckInfo, err = CheckDayReportPermission(user, productAuthOk)
		if err != nil && err != utils.ErrNoRow {
			errMsg = err.Error()
			err = errors.New("权限查询出错")
			return
		}
	}else if reportInfo.ClassifyNameFirst == "周报"{
		authOk, permissionCheckInfo, newTypeIds, err = CheckWeekReportPermission(user, productAuthOk)
		if err != nil && err != utils.ErrNoRow {
			errMsg = err.Error()
			err = errors.New("权限查询出错")
			return
		}
		for _, v := range newTypeIds {
			if v == reportChapter.TypeId {
				chapterAuthOk = true
			}
		}
		authOk = chapterAuthOk
	}

	var chapterMenu []*response.ReportChapterMenu
	reportChapterItem := new(response.ReportChapterItem)
	reportChapterItem.ReportChapterId = reportChapter.ReportChapterId
	reportChapterItem.ReportId = reportChapter.ReportId
	reportChapterItem.Abstract = reportChapter.Abstract
	reportChapterItem.TypeId = reportChapter.TypeId
	reportChapterItem.Title = reportChapter.Title
	reportChapterItem.ReportId = reportChapter.ReportId
	reportChapterItem.PublishTime = reportChapter.PublishTime
	reportChapterItem.VideoPlaySeconds = reportChapter.VideoPlaySeconds
	reportChapterItem.VideoName = reportChapter.VideoName
	if reportChapter.VideoUrl != "" && reportChapter.VideoName == "" {
		reportChapterItem.VideoName = reportChapter.Title
	}
	reportChapterItem.VideoSize = reportChapter.VideoSize
	videoImgMap := map[string]string{
		"day": "report_list_chen.png",
		"week": "report_list_zhou.png",
	}
	reportChapterItem.VideoImg = utils.ALIYUN_YBIMG_HOST + videoImgMap[reportChapter.ReportType]
	reportChapterItem.TypeName = reportChapter.TypeName
	reportChapterItem.Author = reportChapter.Author
	reportChapterItem.Stage = reportChapter.Stage
	reportChapterItem.ClassifyNameFirst = reportChapter.ClassifyNameFirst
	reportChapterItem.ClassifyIdFirst = reportChapter.ClassifyIdFirst
	// 分享背景图
	reportChapterItem.ShareBgImg = utils.DEFAULT_REPORT_SHARE_BG_IMG
	firstClassify, e := classify.GetByClassifyId(reportInfo.ClassifyIdFirst)
	if e != nil {
		err = errors.New("报告一级分类有误")
		return
	}
	if firstClassify.YbShareBgImg != "" {
		reportChapterItem.ShareBgImg = firstClassify.YbShareBgImg
	}
	var likeNum int64
	var likeEnabled int8
	if authOk {
		reportChapterItem.Content = html.UnescapeString(reportChapter.Content)
		reportChapterItem.VideoUrl = reportChapter.VideoUrl
		//底部菜单切换
		if reportInfo.ClassifyNameFirst == "周报" {
			chapterMenu, err = GetMenuChapter(reportInfo.Id, newTypeIds, reportInfo.ClassifyNameFirst, reportInfo.CreateTime)
		}else{
			chapterMenu, err = GetMenuChapter(reportInfo.Id, typeIds, reportInfo.ClassifyNameFirst, reportInfo.CreateTime)
		}
		//查询点赞数
		likeNum,likeEnabled, _ = services.GetReportLikeByReportIdOldReportId(user.UserID, reportInfo.Id, reportChapter.ReportChapterId,0,0)
		go AddViewRecord(user, reportInfo.Id, reportInfo.ClassifyNameFirst, reportChapterId)
	}else{
		reportChapterItem.ContentSub = html.UnescapeString(reportChapter.ContentSub)
	}

	go AddUserAccessRecord(user, reportInfo.Id, reportInfo.ClassifyNameFirst, reportChapterId, authOk)
	reportChapterDetail = new(response.ReportChapterDetail)
	reportChapterDetail.ReportChapterItem = reportChapterItem
	reportChapterDetail.PermissionCheck = &permissionCheckInfo
	reportChapterDetail.ReportChapterMenuList = chapterMenu
	reportChapterDetail.AuthOk = authOk
	reportChapterDetail.LikeNum = likeNum
	reportChapterDetail.LikeEnabled = likeEnabled
	return
}

func GetMenuChapter(reportId int, typeIds []int, classifyNameFirst string, reportCreateTime time.Time) (reportTypeList response.ReportChapterMenuList, err error)  {
	//查询有效的章节
	typeList, tErr := report_chapter_type.GetEffectTypes()
	if tErr != nil {
		return
	}
	if len(typeList) == 0 {
		err = errors.New("无有效的章节")
		return
	}

	typeMap := make(map[uint64]*report_chapter_type.ReportChapterType)
	for _, v := range typeList {
		typeMap[v.ReportChapterTypeId] = v
	}

	//获取所有当前研报的章节
	chapterList, tErr := report_chapter.GetListByReportIdTypeIds(reportId, typeIds, classifyNameFirst)
	if tErr != nil && tErr != utils.ErrNoRow{
		return
	}
	if len(chapterList) > 0 {
		for _, item := range chapterList {
			if typeItem, ok := typeMap[uint64(item.TypeId)]; ok {
				if reportCreateTime.Before(typeItem.PauseStartTime) || reportCreateTime.After(typeItem.PauseEndTime) {
					temp := new(response.ReportChapterMenu)
					temp.ReportChapterId = item.ReportChapterId
					temp.ReportId = item.ReportId
					temp.ReportChapterTypeName = typeItem.ReportChapterTypeName
					temp.ReportChapterTypeThumb = typeItem.YbBottomIcon
					temp.Sort = typeItem.Sort
					temp.PcSelectedThumb = typeItem.PcSelectedImage
					temp.PcUnselectedThumb = typeItem.PcUnselectedImage
					reportTypeList = append(reportTypeList, temp)
				}
			}
		}
	}
	if len(reportTypeList) > 0{
		sort.Sort(reportTypeList)
	}
	return
}

// CheckWeekReportPermission 验证周报的权限
func CheckWeekReportPermission(userInfo user.UserInfo, productAuthOk bool) (authOk bool, permissionCheckInfo response.PermissionCheckInfo, validTypeIds []int,  err error) {
	var permissionIds []int
	var validPermissionIds []int    //最后允许显示的章节
	if productAuthOk {
		permissionIds, err = chart_permission_chapter_mapping.GetPermissionIdsByWeek()
		if err != nil && err != utils.ErrNoRow {
			return
		}
	}
	authOk, permissionCheckInfo, validPermissionIds, err = company.GetCheckPermission(userInfo.CompanyID, int(userInfo.UserID), permissionIds)
	if err != nil {
		return
	}
	//返回可用的章节列表
	if len(validPermissionIds) > 0 {
		validTypeIds, err = chart_permission_chapter_mapping.GetReportIdsByPermisssionIds(validPermissionIds, "week")
	}
	return
}

// CheckDayReportPermission 验证晨报的权限
func CheckDayReportPermission(userInfo user.UserInfo, productAuthOk bool) (authOk bool, permissionCheckInfo response.PermissionCheckInfo, err error) {
	if productAuthOk {
		authOk = true
		return
	}
	authOk, permissionCheckInfo,_, err = company.GetCheckPermission(userInfo.CompanyID, int(userInfo.UserID), []int{})
	return
}


// GetReportChapterVideoList 根据报告获取章节的音频列表
func GetReportChapterVideoList(permissionIds []int, classifyName string, list []*report.Report) (videoMap map[int][]*response.VideoListItem, weekAuthMap map[int]bool, errMsg string, err error) {
	videoMap = make(map[int][]*response.VideoListItem)
	weekAuthMap = make(map[int]bool)
	var reportIds []int
	reportMap := make(map[int]*report.Report)
	for _, reportInfo := range list {
		reportMap[reportInfo.Id] = reportInfo
		reportIds = append(reportIds, reportInfo.Id)
	}
	// 查询有效的章节
	//查询有效的章节
	typeList, tErr := report_chapter_type.GetEffectTypes()
	if tErr != nil {
		errMsg = tErr.Error()
		err = errors.New("章节类型查询出错")
		return
	}
	if len(typeList) == 0 {
		err = errors.New("无有效的章节")
		return
	}

	typeMap := make(map[int]*report_chapter_type.ReportChapterType)
	var typeIds []int
	for _, v := range typeList {
		typeMap[int(v.ReportChapterTypeId)] = v
		typeIds = append(typeIds, int(v.ReportChapterTypeId))
	}

	var chapters []*report_chapter.ReportChapter
	if classifyName == "周报" {
		// 查询用户有权限的章节ID
		newTypeIds, tErr := GetWeekTypeIdsByPermissionIds(permissionIds, typeIds)
		if tErr != nil {
			errMsg = tErr.Error()
			err = errors.New("查询章节类型权限出错")
			return
		}
		// 查询章节列表
		chapters, err = report_chapter.GetByTypeIdsAndReportIds(newTypeIds, reportIds, classifyName)
	}else{
		// 查询章节列表
		chapters, err = report_chapter.GetByTypeIdsAndReportIds(typeIds, reportIds, classifyName)
	}
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询章节出错")
		return
	}
	for _, v := range chapters {
		if classifyName == "周报" {
			weekAuthMap[v.ReportId] = true
		}
		if temp, ok := typeMap[v.TypeId]; ok && v.VideoUrl != "" {
			if reportDetail, ok1 := reportMap[v.ReportId]; ok1 {
				reportDate := reportDetail.CreateTime
				if reportDate.Before(temp.PauseStartTime) || reportDate.After(temp.PauseEndTime) {
					videoItem := new(response.VideoListItem)
					videoItem.VideoPlaySeconds = v.VideoPlaySeconds
					videoItem.VideoName = v.VideoName
					if v.VideoName == "" {
						videoItem.VideoName = v.Title
					}
					videoItem.VideoUrl = v.VideoUrl
					videoItem.Sort = v.Sort
					videoMap[v.ReportId] = append(videoMap[v.ReportId], videoItem)
				}
			}

		}
	}

	return
}