package services

import (
	"errors"
	"gorm.io/gorm"
	"hongze/hongze_yb/models/tables/company_product"
	"hongze/hongze_yb/models/tables/rddp/report"
	"hongze/hongze_yb/models/tables/rddp/report_chapter"
	"hongze/hongze_yb/models/tables/research_report_type"
	"hongze/hongze_yb/models/tables/voice_broadcast_statistics"
	"hongze/hongze_yb/models/tables/yb_community_audio_listen_log"
	"hongze/hongze_yb/models/tables/yb_community_video_play_log"
	"hongze/hongze_yb/models/tables/yb_like"
	"hongze/hongze_yb/services/user"
	"hongze/hongze_yb/utils"
	"strings"
)

// 访问日志来源
const (
	ViewLogSourceQuestion       = iota + 1 // 问答社区-1
	ViewLogSourceVoiceBroadcast            // 语音播报-2
	ViewLogSourceVideo                     // 视频社区-3
	ViewLogSourceRoadVideo                 // 路演视频-4
)

// GetReportIdReportChapterIdByOldReportId 根据老报告的ID查询对应的新报告ID
func GetReportIdReportChapterIdByOldReportId(oldReportId, oldReportChapterId uint64) (reportId int, reportChapterId int, err error, errMsg string) {
	var reportNew *report.Report
	if oldReportChapterId > 0 {
		//查询章节详情，根据章节类型ID和老报告ID，根据老报告ID，查询新报告ID，根据新报告ID和type_id 找到新的章节ID
		var oldReportChapter *research_report_type.ResearchReportTypeInfo
		var reportChapterNew *report_chapter.ReportChapter
		oldReportChapter, err = research_report_type.GetResearchReportTypeInfo(oldReportChapterId)
		if err != nil {
			errMsg = err.Error()
			err = errors.New("找不到报告章节")
			return
		}
		if oldReportChapter == nil {
			err = errors.New("找不到报告章节")
			return
		}
		if oldReportId != oldReportChapter.ResearchReportID {
			err = errors.New("报告ID和章节ID不一致")
			return
		}
		//判断是否是晨报或者周报的章节ID，双周报的章节ID不记录
		if oldReportChapter.TypeID == 0 {
			err = errors.New("只允许传晨报和周报的章节ID")
			return
		}
		reportNew, err = report.GetReportByOldReportId(oldReportChapter.ResearchReportID)
		if err != nil {
			errMsg = err.Error()
			//err = errors.New("找不到新版报告")
			return
		}
		if reportNew.Id <= 0 {
			//err = errors.New("找不到新版报告")
			return
		}
		reportChapterNew, err = report_chapter.GetChapterByReportIdTypeId(reportNew.Id, oldReportChapter.TypeID)
		if err != nil {
			errMsg = err.Error()
			return
		}
		if reportChapterNew.ReportChapterId <= 0 {
			//err = errors.New("找不到新版章节")
			return
		}
		reportId = reportNew.Id
		reportChapterId = reportChapterNew.ReportChapterId
		return
	} else if oldReportId > 0 {
		// 查询新报告ID
		reportNew, err = report.GetReportByOldReportId(oldReportId)
		if err != nil {
			errMsg = err.Error()
			//err = errors.New("找不到新版报告")
			return
		}
		reportId = reportNew.Id
		return
	}
	return
}

// CheckReportExistByReportIdReportChapterId 评论和点赞时，校验传入的报告ID是否正确
func CheckReportExistByReportIdReportChapterId(reportId, reportChapterId int) (err error, errMsg string) {
	reportInfo, err := report.GetByReportId(reportId)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询报告出错")
		return
	}
	if reportInfo.Id <= 0 {
		err = errors.New("报告不存在")
		return
	}

	//if reportInfo.HasChapter == 1 && reportChapterId <= 0 {
	//	err = errors.New("请输入报告章节ID")
	//	return
	//}

	if reportChapterId > 0 {
		reportChapterInfo, tErr := report_chapter.GetTypeIdById(reportChapterId)
		if tErr != nil {
			errMsg = tErr.Error()
			err = errors.New("查询章节失败")
			return
		}

		if reportChapterInfo.ReportChapterId == 0 {
			err = errors.New("章节不存在或者未发布")
			return
		}

		if reportChapterInfo.ReportId != reportId {
			err = errors.New("章节ID和报告ID不匹配")
			return
		}
	}
	return
}

// CheckSimpleCompanyProduct 校验用户是否FICC产品的已购或者试用状态
func CheckSimpleCompanyProduct(userinfo user.UserInfo) (err error, errMsg string) {
	// 判断用户状态是否是正常和永续
	var productAuthOk bool
	companyProduct, err := company_product.GetByCompany2ProductId(userinfo.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
			}
		}
	}
	if !productAuthOk {
		err = errors.New("无权操作")
		return
	}
	return
}

func GetReportLikeByReportIdOldReportId(userId uint64, reportId, reportChapterId int, oldReportId, oldReportChapterId int) (likeNum int64, likeEnabled int8, err error) {
	// 根据老报告找到新报告的ID
	if reportId == 0 && oldReportId > 0 {
		reportId, reportChapterId, err, _ = GetReportIdReportChapterIdByOldReportId(uint64(oldReportId), uint64(oldReportChapterId))
	}
	//查询总的点赞数
	if reportId > 0 {
		likeNum, err = yb_like.GetLikeNumByReportId(reportId, reportChapterId)
	} else if oldReportId > 0 {
		likeNum, err = yb_like.GetLikeNumByOldReportId(oldReportId, oldReportChapterId)
	}

	if err != nil {
		err = errors.New("查询点赞数出错")
		return
	}

	//查询用户对研报的点赞状态
	var likeItem *yb_like.YbLike
	if reportId > 0 {
		likeItem, err = yb_like.GetLikeByUserIdAndReportId(userId, reportId, reportChapterId)
	} else {
		likeItem, err = yb_like.GetLikeByUserIdAndOldReportId(userId, oldReportId, oldReportChapterId)
	}
	if err != nil {
		err = errors.New("查询用户点赞记录出错")
		return
	}
	likeEnabled = likeItem.Enabled
	return
}

// UpdateViewLogBySource 更新各模块访问日志
// Source: 来源:1-问答社区; 2-语音播报; 3-视频社区; 4-路演视频...
func UpdateViewLogBySource(userId, viewLogId, stopSeconds, source int) (err error) {
	if viewLogId <= 0 || source <= 0 {
		return
	}

	switch source {
	case ViewLogSourceQuestion:
		viewLog := new(yb_community_audio_listen_log.YbCommunityAudioListenLog)
		viewLog.Id = viewLogId
		item, e := viewLog.GetById()
		if e != nil {
			if e == gorm.ErrRecordNotFound {
				return
			}
			err = errors.New("获取访问日志失败, Err: " + e.Error())
			return
		}
		if item.UserID != userId {
			err = errors.New("用户不一致, 更新日志失败")
			return
		}
		item.StopSeconds = stopSeconds
		err = item.Update([]string{"stop_seconds"})
	case ViewLogSourceVoiceBroadcast:
		viewLog := new(voice_broadcast_statistics.VoiceBroadcastStatistics)
		viewLog.Id = viewLogId
		item, e := viewLog.GetById()
		if e != nil {
			if e == gorm.ErrRecordNotFound {
				return
			}
			err = errors.New("获取访问日志失败, Err: " + e.Error())
			return
		}
		if item.UserId != userId {
			err = errors.New("用户不一致, 更新日志失败")
			return
		}
		item.StopSeconds = stopSeconds
		err = item.Update([]string{"stop_seconds"})
	case ViewLogSourceVideo, ViewLogSourceRoadVideo:
		viewLog := new(yb_community_video_play_log.YbCommunityVideoPlayLog)
		viewLog.ID = viewLogId
		item, e := viewLog.GetById()
		if e != nil {
			if e == gorm.ErrRecordNotFound {
				return
			}
			err = errors.New("获取访问日志失败, Err: " + e.Error())
			return
		}
		if item.UserID != userId {
			err = errors.New("用户不一致, 更新日志失败")
			return
		}
		item.StopSeconds = stopSeconds
		err = item.Update([]string{"stop_seconds"})
	default:
		err = errors.New("来源有误")
		return
	}
	return
}
