package report

import (
	"encoding/json"
	"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/response/purchase"
	"hongze/hongze_yb/models/tables/chart_permission_search_key_word_mapping"
	"hongze/hongze_yb/models/tables/company_product"
	"hongze/hongze_yb/models/tables/daily_base_column"
	"hongze/hongze_yb/models/tables/rddp/chart_permission"
	"hongze/hongze_yb/models/tables/rddp/chart_permission_chapter_mapping"
	"hongze/hongze_yb/models/tables/rddp/classify"
	"hongze/hongze_yb/models/tables/rddp/classify_menu"
	"hongze/hongze_yb/models/tables/rddp/report"
	"hongze/hongze_yb/models/tables/rddp/report_chapter"
	"hongze/hongze_yb/models/tables/rddp/report_chapter_ticker"
	"hongze/hongze_yb/models/tables/rddp/report_ppt_img"
	"hongze/hongze_yb/models/tables/rddp/smart_report_resource"
	"hongze/hongze_yb/models/tables/report_chapter_type"
	"hongze/hongze_yb/models/tables/report_chapter_type_permission"
	"hongze/hongze_yb/models/tables/user_report_chapter_set"
	"hongze/hongze_yb/models/tables/yb_road_video"
	"hongze/hongze_yb/services"
	"hongze/hongze_yb/services/base_config"
	"hongze/hongze_yb/services/collection"
	"hongze/hongze_yb/services/company"
	elasticService "hongze/hongze_yb/services/elastic"
	"hongze/hongze_yb/services/user"
	"hongze/hongze_yb/utils"
	"html"
	"sort"
	"strconv"
	"strings"
	"time"
)

// GetLatestClassReport 已购列表最新报告
func GetLatestClassReport(permissionIds []int, userId uint64) (purchaseList []*purchase.PurchaseListItem, err error) {
	var errMsg string
	defer func() {
		if sysErr := recover(); sysErr != nil {
			err = errors.New("系统错误")
			global.LOG.Critical(fmt.Sprintf("GetLatestClassReport: userId=%d, err:%s，sysErr:%s", userId, err.Error(), sysErr))
		}
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("GetLatestClassReport: userId=%d, err:%s， errMsg:%s", userId, err.Error(), errMsg))
		}
	}()
	//获取所有分类信息
	classifys, err := classify.GetSimpleAll()
	if err != nil {
		errMsg = err.Error()
		err = errors.New("分类查询出错")
		return
	}
	classifyFirstIconMap := make(map[int]string)
	//classifySecondNameMap := make(map[int]int)
	classifyFirstIdMap := make(map[int]bool)
	classifySecondIdMap := make(map[int]bool)
	for _, v := range classifys {
		if v.ParentId == 0 {
			classifyFirstIdMap[v.Id] = true
			classifyFirstIconMap[v.Id] = v.YbIconUrl
		} else {
			classifySecondIdMap[v.Id] = true
			//classifySecondNameMap[v.Id] = v.Id
		}
	}
	//获取最新的晨报
	dayReport, err := report.GetLatestDay()
	if err != nil {
		errMsg = err.Error()
		err = errors.New("晨报查询出错")
		return
	}
	//获取最新的有权限的周报
	//typeIds, err := report_chapter_type.GetEffectTypeID()
	typeIds, err := report_chapter_type_cache.GetEffectTypeID()
	if err != nil {
		errMsg = err.Error()
		err = errors.New("晨报查询出错")
		return
	}
	weekReport, err := GetLatestWeek(permissionIds, typeIds)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("周报查询出错")
		return
	}
	// 有权限的二级分类
	var reports []*report.Report
	var classifyIdSeconds []int
	classifyIdSecondMap := make(map[int]bool)
	// 获取晨报和周报以外的其他报告
	// 获取有权限的二级分类
	chartPermissions, err := chart_permission_search_key_word_mapping.GetChartPermissionByFrom("rddp")
	if err != nil {
		errMsg = err.Error()
		err = errors.New("分类权限查询出错")
		return
	}
	if len(chartPermissions) > 0 {
		for _, v := range chartPermissions {
			for _, myPerId := range permissionIds {
				if v.ChartPermissionId == myPerId {
					if classifySecondIdMap[v.ClassifyId] {
						if _, ok := classifyIdSecondMap[v.ClassifyId]; !ok {
							classifyIdSeconds = append(classifyIdSeconds, v.ClassifyId)
							classifyIdSecondMap[v.ClassifyId] = true
						}
					}
					break
				}
			}
		}
	}
	reports, err = report.GetLatestClassReportsByClassifyIdSeconds(classifyIdSeconds)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("二级分类最新报告查询出错")
		return
	}
	if dayReport.Id > 0 {
		reports = append(reports, dayReport)
	}
	if weekReport != nil && weekReport.Id > 0 {
		reports = append(reports, weekReport)
	}
	//获取未读数
	unReadItem, tErr := GetUnRead(classifyIdSeconds, userId)
	if tErr != nil {
		err = tErr
		return
	}

	if len(reports) > 0 {
		otherLatestItem := new(purchase.PurchaseListItem)
		// 处理其他报告（）
		for _, v := range reports {
			temp := new(purchase.PurchaseListItem)
			temp.ReportId = v.Id
			temp.ClassifyIdFirst = v.ClassifyIdFirst
			temp.ClassifyNameFirst = v.ClassifyNameFirst
			temp.Stage = v.Stage
			temp.Title = v.Title
			temp.ClassifyIdSecond = v.ClassifyIdSecond
			temp.ClassifyNameSecond = v.ClassifyNameSecond
			temp.Time = v.PublishTime
			if temp.ClassifyNameFirst == "大事点评" || temp.ClassifyNameFirst == "会议纪要" || temp.ClassifyNameFirst == "年报合集" {
				if otherLatestItem.Time.Format(utils.FormatDateTime) > v.PublishTime.Format(utils.FormatDateTime) {
					continue
				}
				temp.Unread = unReadItem["大事点评"] + unReadItem["会议纪要"] + unReadItem["年报合集"]
				temp.Content = fmt.Sprintf("【第%d期|FICC】%s", temp.Stage, temp.ClassifyNameFirst)
				temp.ImgUrl = "https://hzstatic.hzinsights.com/static/yb_wx/purchase_icon_other.png"
				otherLatestItem = temp
			}
		}
		for _, v := range reports {
			if v.ClassifyNameFirst != "晨报" && v.ClassifyNameFirst != "周报" {
				// 报告的分类不存在
				if !classifyFirstIdMap[v.ClassifyIdFirst] || !classifyIdSecondMap[v.ClassifyIdSecond] {
					continue
				}
			}
			temp := new(purchase.PurchaseListItem)
			temp.ReportId = v.Id
			temp.ClassifyIdFirst = v.ClassifyIdFirst
			temp.ClassifyNameFirst = v.ClassifyNameFirst
			temp.Stage = v.Stage
			temp.Title = v.Title
			temp.ClassifyIdSecond = v.ClassifyIdSecond
			temp.ClassifyNameSecond = v.ClassifyNameSecond
			temp.Time = v.PublishTime
			temp.Unread = unReadItem[temp.ClassifyNameFirst]
			if imgUrl, ok := classifyFirstIconMap[temp.ClassifyIdFirst]; ok {
				temp.ImgUrl = imgUrl
			}
			if temp.ClassifyNameFirst == "晨报" || temp.ClassifyNameFirst == "周报" { //晨报或者周报，查询最新的章节信息
				temp.Content = fmt.Sprintf("【第%d期|FICC】%s", temp.Stage, temp.Title)
			} else if temp.ClassifyNameFirst == "大事点评" || temp.ClassifyNameFirst == "会议纪要" || temp.ClassifyNameFirst == "年报合集" {
				continue
			} else {
				if temp.ClassifyNameFirst != temp.ClassifyNameSecond { //包含二级分类
					temp.Content = fmt.Sprintf("【第%d期|FICC| %s】%s", temp.Stage, temp.ClassifyNameSecond, temp.ClassifyNameFirst)
				} else { //无二级分类
					temp.Content = fmt.Sprintf("【第%d期|FICC】%s", temp.Stage, temp.ClassifyNameFirst)
				}
			}

			purchaseList = append(purchaseList, temp)
		}
		if otherLatestItem.ReportId > 0 {
			purchaseList = append(purchaseList, otherLatestItem)
		}
	}
	return
}

// GetPurchaseDetail 已购详情页面
func GetPurchaseDetail(permissionIds []int, userId uint64, classifyIdFirst int, pageIndex, pageSize int) (ret *purchase.DetailResp, err error) {
	var errMsg string
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("GetPurchaseDetail: userId=%d, err:%s， errMsg:%s", userId, err.Error(), errMsg))
		}
	}()
	var reports []*report.Report
	var weekReportIds []int

	classifyInfo, err := classify.GetByClassifyId(classifyIdFirst)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("分类查询出错")
		return
	}

	if classifyInfo.Id == 0 {
		err = errors.New("分类不存在")
		return
	}

	classifyNameFirst := classifyInfo.ClassifyName
	offset := (pageIndex - 1) * pageSize
	var total int64
	var classifyIdSeconds []int

	if classifyNameFirst == "晨报" {
		//分类获取
		reports, err = report.GetListByClassifyIdFirst(classifyIdFirst, offset, pageSize)
		if err != nil {
			errMsg = err.Error()
			err = errors.New("晨报查询出错")
			return
		}
		total, err = report.GetListCountByClassifyIdFirst(classifyIdFirst)
		if err != nil {
			errMsg = err.Error()
			err = errors.New("查询报告总数出错")
			return
		}
	} else {
		if classifyNameFirst == "周报" {
			newTypeIds, tErr := GetWeekTypeIdsByPermissionIds(permissionIds, []int{})
			if tErr != nil {
				return
			}
			weekReportIds, err = report_chapter.GetReportIdsByTypeIdsAndClass(newTypeIds, classifyNameFirst)
			//分类获取
			reports, err = report.GetListByIDsAndClassifyIdFirst(weekReportIds, classifyIdFirst, offset, pageSize)
			if err != nil {
				return
			}
			total, err = report.GetListCountByIDsAndClassifyIdFirst(weekReportIds, classifyIdFirst)
			if err != nil {
				errMsg = err.Error()
				err = errors.New("查询报告总数出错")
				return
			}
		} else {
			//获取有权限的二级分类
			var classifyNameSeconds []string
			chartPermissions, tErr := chart_permission_search_key_word_mapping.GetChartPermissionByFrom("rddp")
			if tErr != nil {
				errMsg = tErr.Error()
				err = errors.New("分类权限查询出错")
				return
			}
			if len(chartPermissions) > 0 {
				for _, v := range chartPermissions {
					for _, myPerId := range permissionIds {
						if v.ChartPermissionId == myPerId {
							if classifyNameFirst == "大事点评" || classifyNameFirst == "会议纪要" || classifyNameFirst == "年报合集" {
								if v.KeyWord == "大事点评" || v.KeyWord == "会议纪要" || v.KeyWord == "年报合集" { //筛选出用户有权限的二级分类ID
									classifyNameSeconds = append(classifyNameSeconds, v.KeyWord)
								}
							} else {
								classifyNameSeconds = append(classifyNameSeconds, v.KeyWord)
							}
							break
						}
					}
				}
			}
			//获取所有二级分类的id
			if classifyNameFirst == "大事点评" || classifyNameFirst == "会议纪要" || classifyNameFirst == "年报合集" {
				classifyIdSeconds, tErr = classify.GetOtherSecondIds([]string{"大事点评", "会议纪要", "年报合集"})
			} else {
				classifyIdSeconds, tErr = classify.GetIdsByClassifyNameAndParentId(classifyNameSeconds, classifyIdFirst)
			}

			if tErr != nil {
				errMsg = tErr.Error()
				err = errors.New("二级分类查询出错")
				return
			}
			if len(classifyIdSeconds) > 0 {
				//分类获取
				reports, err = report.GetListByClassifyIdSeconds(classifyIdSeconds, offset, pageSize)
				if err != nil {
					return
				}
				total, err = report.GetListCountByClassifyIdSeconds(classifyIdSeconds)
				if err != nil {
					errMsg = err.Error()
					err = errors.New("查询报告总数出错")
					return
				}
			}
		}
	}

	var list []*purchase.Detail
	ret = new(purchase.DetailResp)
	if len(reports) > 0 {
		var viewReportIds []int
		for _, v := range reports {
			viewReportIds = append(viewReportIds, v.Id)
			temp := new(purchase.Detail)
			temp.ReportId = v.Id
			temp.ClassifyIdFirst = v.ClassifyIdFirst
			temp.ClassifyNameFirst = v.ClassifyNameFirst
			temp.Title = v.Title
			temp.ClassifyIdSecond = v.ClassifyIdSecond
			temp.ClassifyNameSecond = v.ClassifyNameSecond
			temp.Stage = v.Stage
			temp.ImgUrl = classifyInfo.YbBgUrl
			if temp.ClassifyNameFirst == "晨报" || temp.ClassifyNameFirst == "周报" { //晨报或者周报，查询最新的章节信息
				temp.Content = fmt.Sprintf("【第%d期|FICC】%s", temp.Stage, temp.Title)
				temp.TopName = temp.Title
			} else {
				if temp.ClassifyNameFirst != temp.ClassifyNameSecond { //包含二级分类
					temp.Content = fmt.Sprintf("【第%d期|FICC| %s】%s", temp.Stage, temp.ClassifyNameSecond, temp.ClassifyNameFirst)
					temp.TopName = temp.ClassifyNameSecond
				} else {
					temp.Content = fmt.Sprintf("【第%d期|FICC】%s", temp.Stage, temp.ClassifyNameFirst)
					temp.TopName = temp.ClassifyNameFirst
				}
			}
			temp.Time = v.PublishTime
			list = append(list, temp)
		}
	}
	ret.List = list
	ret.Paging = response.GetPaging(pageIndex, pageSize, int(total))
	// 执行一个协程任务，新增用户浏览记录
	//_, tErr := BatchInsertReportView(weekReportIds, userId, classifyNameFirst, classifyIdSeconds)
	go BatchInsertReportView(userId, weekReportIds, classifyNameFirst, classifyIdSeconds)
	/*if tErr != nil {
		err = tErr
		return
	}*/
	return
}

// 获取报告详情
func GetReportDetail(userinfo user.UserInfo, reportId int) (reportDetail response.ReportDetail, err error) {
	var errMsg string
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("GetReportDetail: userId=%d, err:%s， errMsg:%s", userinfo.UserID, err.Error(), errMsg))
		}
	}()
	// 判断用户状态是否是正常和永续
	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
			}
		}
	}
	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.State != 2 && reportInfo.State != 6 {
		err = errors.New("报告未发布")
		return
	}
	// 获取最小分类
	minClassifyId, _, err := GetMinClassify(reportInfo)

	// 判断报告是否属于专栏报告
	firstClassify, e := classify.GetByClassifyId(reportInfo.ClassifyIdFirst)
	if e != nil {
		err = errors.New("报告一级分类有误")
		return
	}

	// 最小分类
	var minClassify *classify.Classify
	if reportInfo.ClassifyIdFirst == minClassifyId {
		minClassify = firstClassify
	} else {
		minClassify, e = classify.GetByClassifyId(minClassifyId)
		if e != nil {
			err = errors.New("报告最小层级分类有误")
			return
		}
	}

	//判断权限

	var authOk bool
	var permissionCheckInfo response.PermissionCheckInfo
	//var vaildWeekTypeIds []int
	var reportChapterIdList []int
	if reportInfo.HasChapter == 1 {
		if reportInfo.ClassifyNameFirst == "晨报" {
			authOk, permissionCheckInfo, err = CheckDayReportPermission(userinfo, productAuthOk)
		} else {
			authOk, permissionCheckInfo, _, reportChapterIdList, err = CheckWeekReportPermission(userinfo, reportId, productAuthOk)
		}
	} else {
		authOk, permissionCheckInfo, err = CheckReportPermission(userinfo, reportId, productAuthOk)
	}

	if err != nil {
		return
	}

	reportItem := new(response.ReportItem)
	reportItem.ReportId = reportInfo.Id
	reportItem.Title = reportInfo.Title
	reportItem.PublishTime = reportInfo.PublishTime
	reportItem.ClassifyNameFirst = reportInfo.ClassifyNameFirst
	reportItem.ClassifyNameSecond = reportInfo.ClassifyNameSecond
	reportItem.Stage = reportInfo.Stage
	reportItem.Abstract = reportInfo.Abstract
	reportItem.ContentSub = html.UnescapeString(reportInfo.ContentSub)
	reportItem.Frequency = reportInfo.Frequency
	reportItem.VideoName = reportInfo.VideoName
	reportItem.HasChapter = reportInfo.HasChapter
	reportItem.ReportLayout = reportInfo.ReportLayout
	reportItem.HeadImg = reportInfo.HeadImg
	reportItem.EndImg = reportInfo.EndImg
	reportItem.CanvasColor = reportInfo.CanvasColor
	reportItem.RaiReportId = reportInfo.RaiReportId

	// 版头版尾样式
	{
		if reportInfo.HeadResourceId > 0 {
			headResource, tmpErr := smart_report_resource.GetResourceItemById(reportInfo.HeadResourceId)
			if tmpErr != nil && tmpErr != utils.ErrNoRow {
				err = tmpErr
				return
			}
			if headResource != nil && headResource.ResourceID > 0 {
				reportItem.HeadImg = headResource.ImgURL
				reportItem.HeadStyle = headResource.Style
			}
		}

		if reportInfo.EndResourceId > 0 {
			endResource, tmpErr := smart_report_resource.GetResourceItemById(reportInfo.EndResourceId)
			if tmpErr != nil && tmpErr != utils.ErrNoRow {
				err = tmpErr
				return
			}
			if endResource != nil && endResource.ResourceID > 0 {
				reportItem.EndImg = endResource.ImgURL
				reportItem.EndStyle = endResource.Style
			}
		}
	}

	if reportInfo.VideoName == "" && reportInfo.VideoUrl != "" {
		reportItem.VideoName = reportInfo.Title
	}
	reportItem.VideoSize = reportInfo.VideoSize
	reportItem.VideoPlaySeconds = reportInfo.VideoPlaySeconds
	reportItem.Author = reportInfo.Author
	// 分享背景图取二级分类配图, 二级没有配图时使用一级配图, 一级也没有使用默认图
	reportItem.ShareBgImg = utils.DEFAULT_REPORT_SHARE_BG_IMG
	secondClassify, e := classify.GetByClassifyId(reportInfo.ClassifyIdSecond)
	if e != nil {
		err = errors.New("报告二级分类有误")
		return
	}
	if secondClassify.YbShareBgImg != "" {
		reportItem.ShareBgImg = secondClassify.YbShareBgImg
	} else {
		if firstClassify.YbShareBgImg != "" {
			reportItem.ShareBgImg = firstClassify.YbShareBgImg
		}
	}
	var reportTypeList []*response.ReportChapterListItem

	if reportInfo.HasChapter == 1 {
		//（晨报和周报的banner图）
		if reportInfo.ClassifyNameFirst == "晨报" {
			reportItem.BannerUrl = utils.ALIYUN_YBIMG_HOST + "report_banner_day.jpg"
		} else {
			reportItem.BannerUrl = utils.ALIYUN_YBIMG_HOST + "report_banner_week.jpg"
		}

		// 如果还没有配置banner图，则取晨报的
		if reportItem.BannerUrl == `` {
			reportItem.BannerUrl = utils.ALIYUN_YBIMG_HOST + "report_banner_day.jpg"
		}

		if authOk {
			reportTypeList, err = GetChapterListByReportChapterIdList(reportInfo.ClassifyNameFirst, reportInfo.Id, reportChapterIdList)
			if err != nil {
				return
			}
		}
	} else {
		// 音频播放条图片用分类图片
		reportItem.VideoImg = utils.HZ_DEFAULT_AVATAR
		permissionIds, tmpErr := chart_permission_search_key_word_mapping.GetChartPermissionIdsByKeyWord(reportInfo.ClassifyIdSecond)
		if tmpErr != nil {
			errMsg = tmpErr.Error()
			err = errors.New("查询报告权限失败")
			return
		}
		if len(permissionIds) > 0 {
			chartPermission, tmpErr := chart_permission.GetListByIds(permissionIds)
			if tmpErr != nil {
				errMsg = tmpErr.Error()
				err = errors.New("查询品种信息失败")
				return
			}
			lenChart := len(chartPermission)
			for i := 0; i < lenChart; i++ {
				if chartPermission[i].YbImgUrl != "" {
					reportItem.VideoImg = utils.ALIYUN_YBIMG_HOST + chartPermission[i].YbImgUrl
					break
				}
			}
		}
	}
	//如果有权限则展示content
	var likeNum int64
	var likeEnabled int8
	if authOk {
		go AddViewRecord(userinfo, reportInfo.Id, reportInfo.ClassifyNameFirst, 0)
		reportItem.Content = html.UnescapeString(reportInfo.Content)
		reportItem.VideoUrl = reportInfo.VideoUrl
		//查询点赞数
		likeNum, likeEnabled, _ = services.GetReportLikeByReportIdOldReportId(userinfo.UserID, reportInfo.Id, 0, 0, 0)
	}

	//处理章节品种，音频开关
	{
		chapterSetList, err := user_report_chapter_set.GetUserReportChapterSet(userinfo.UserID)
		if err != nil {
			return reportDetail, err
		}

		setList := make([]*user_report_chapter_set.UserReportChapterSet, 0)
		reportTypeLen := len(reportTypeList)
		if len(chapterSetList) == 0 {
			for _, v := range reportTypeList {
				setItem := new(user_report_chapter_set.UserReportChapterSet)
				setItem.UserId = userinfo.UserID
				setItem.TypeId = v.TypeId
				setItem.TypeName = v.TypeName
				setItem.CreateTime = time.Now()
				setItem.ModifyTime = time.Now()
				setItem.IsClose = 0
				setList = append(setList, setItem)
			}
		} else {
			chapterSetMap := make(map[int]int)
			for _, v := range chapterSetList {
				chapterSetMap[v.TypeId] = v.IsClose
			}
			for i := 0; i < reportTypeLen; i++ {
				typeItem := reportTypeList[i]
				if findIsClose, ok := chapterSetMap[typeItem.TypeId]; ok {
					reportTypeList[i].IsClose = findIsClose
				} else {
					setItem := new(user_report_chapter_set.UserReportChapterSet)
					setItem.UserId = userinfo.UserID
					setItem.TypeId = typeItem.TypeId
					setItem.TypeName = typeItem.TypeName
					setItem.CreateTime = time.Now()
					setItem.ModifyTime = time.Now()
					setItem.IsClose = 0
					setList = append(setList, setItem)
				}
			}
		}
		if len(setList) > 0 {
			err = user_report_chapter_set.AddUserReportChapterSet(setList)
			if err != nil {
				return reportDetail, err
			}
		}
	}

	//新增用户访问日志
	go AddUserAccessRecord(userinfo, reportInfo.Id, reportInfo.ClassifyNameFirst, 0, authOk)
	reportDetail.ReportInfo = reportItem
	reportDetail.ReportChapterList = reportTypeList
	reportDetail.PermissionCheck = &permissionCheckInfo
	reportDetail.AuthOk = authOk
	reportDetail.LikeNum = likeNum
	reportDetail.LikeEnabled = likeEnabled
	reportDetail.ReportShowType = int(firstClassify.ShowType)
	reportDetail.ReportDetailShowType = int(minClassify.ReportDetailShowType)
	if reportInfo.RaiReportId > 0 {
		reportDetail.RaiReportUrl = fmt.Sprintf("%s/v2/articles/%d?token=%s", global.CONFIG.RaiReportLib.ServerUrl, reportInfo.RaiReportId, global.CONFIG.RaiReportLib.Token)
	}

	// 如果分类配置是列表展示，那么就移除content内容
	if minClassify.ReportDetailShowType == 2 {
		for _, v := range reportTypeList {
			v.Content = ``
		}
	} else {
		for _, v := range reportTypeList {
			v.Content = html.UnescapeString(v.Content)
		}
	}

	// 图表授权token
	{
		isOpenChartExpired, e := base_config.CheckIsOpenChartExpired()
		if e != nil {
			err = errors.New("获取图表是否开启鉴权失败,err：" + e.Error())
			return
		}

		if isOpenChartExpired {
			tokenMap := make(map[string]string)
			reportDetail.ReportInfo.Content = HandleReportContent(reportDetail.ReportInfo.Content, "add", tokenMap)
			reportDetail.ReportInfo.ContentSub = HandleReportContent(reportDetail.ReportInfo.ContentSub, "add", tokenMap)
			for _, v := range reportTypeList {
				v.Content = HandleReportContent(v.Content, "add", tokenMap)
			}
		}
	}

	// 收藏
	collectionId, e := collection.GetUserCollectByItem(int(userinfo.UserID), collection.CollectionTypeReport, reportId, 0)
	if e != nil {
		err = e
		return
	}
	reportDetail.CollectionId = collectionId

	// 绑定的路演视频
	roadVideo, e := yb_road_video.GetItemByReportId(reportId)
	if e != nil && e != utils.ErrNoRow {
		err = e
		return
	}
	if roadVideo != nil && roadVideo.RoadVideoID > 0 {
		reportDetail.RoadVideoId = roadVideo.RoadVideoID
	}
	return
}

// CheckReportPermission 验证用户查看报告的权限
func CheckReportPermission(userInfo user.UserInfo, reportId int, productAuthOk bool) (authOk bool, permissionCheckInfo response.PermissionCheckInfo, err error) {
	var permissionIds []int
	if productAuthOk {
		permissionIds, err = chart_permission_chapter_mapping.GetPermissionIdsByReportId(reportId, "rddp")
		if err != nil && err != utils.ErrNoRow {
			return
		}
	}
	authOk, permissionCheckInfo, _, err = company.GetCheckPermission(userInfo.CompanyID, int(userInfo.UserID), permissionIds)
	return
}

// GetReportList 获取报告列表
func GetReportList(user user.UserInfo, keyWord string, classifyIdFirst, classifyIdSecond, pageIndex, pageSize, classifyMenuId int) (ret *response.ReportList, err error) {
	var errMsg string
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("GetReportList: userId=%d, err:%s， errMsg:%s", user.UserID, err.Error(), errMsg))
		}
	}()

	// 判断用户状态是否是正常和永续
	var productAuthOk bool
	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
			}
		}
	}

	var condition string
	pars := make([]interface{}, 0)

	classifyParent, err := classify.GetByClassifyId(classifyIdFirst)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("分类查询出错")
		return
	}
	if classifyParent.Id == 0 {
		err = errors.New("该分类不存在")
		return
	}
	condition = `classify_id_first = ? and state IN (2, 6) and is_public_publish=1 `
	pars = append(pars, classifyIdFirst)

	// 子目录
	menuClassifyIds := make([]int, 0)
	menuClassifyLen := 0
	if classifyMenuId > 0 {
		ids, e := classify_menu.GetClassifyIdsByMenuId(classifyMenuId)
		if e != nil {
			err = errors.New("获取子目录关联分类信息失败, Err: " + e.Error())
			return
		}
		menuClassifyIds = ids
		menuClassifyLen = len(menuClassifyIds)
		if menuClassifyLen == 0 {
			condition += ` AND 1 = 2`
		}
	}

	permissionMap := make(map[int][]int)
	checkPermissionMap := make(map[int]bool)
	//permissionImageMap := make(map[string]string)
	chartPermissionImageMap := make(map[int]string)
	var classifyIdSeconds []int
	//var reportImgUrl string

	chartPermissionList, err := chart_permission.GetFiccListExceptTacticByProductId()
	if err != nil {
		errMsg = err.Error()
		err = errors.New("分类查询出错")
		return
	}

	if len(chartPermissionList) > 0 {
		for _, v := range chartPermissionList {
			chartPermissionImageMap[int(v.ChartPermissionID)] = v.YbImgUrl
		}
	}

	if classifyIdSecond > 0 && keyWord == "" {
		classifyInfo, tErr := classify.GetByClassifyId(classifyIdSecond)
		if tErr != nil {
			errMsg = tErr.Error()
			err = errors.New("分类查询出错")
			return
		}
		if classifyInfo.Id == 0 {
			err = errors.New("该二级分类不存在")
			return
		}

		condition += " AND classify_id_second = ?"
		pars = append(pars, classifyIdSecond)
		//查询二级分类对应的权限
		permissionIds, tErr := chart_permission_search_key_word_mapping.GetChartPermissionIdsByKeyWord(classifyIdSecond)
		if tErr != nil {
			errMsg = tErr.Error()
			err = errors.New("分类权限查询出错")
			return
		}
		permissionMap[classifyInfo.Id] = permissionIds
		//if len(permissionIds) > 0 {
		//	for _, v := range permissionIds {
		//		reportImgUrl = chartPermissionImageMap[v]
		//	}
		//}

	} else {
		if classifyParent.HasChild == 0 {
			//reportImgUrl = chartPermissionImageMap[1]
			classifyIdSeconds = append(classifyIdSeconds, 0)
		}

		chartPermissions, tErr := chart_permission_search_key_word_mapping.GetChartPermissionByFrom("rddp")
		if tErr != nil {
			errMsg = tErr.Error()
			err = errors.New("分类权限查询出错")
			return
		}

		if len(chartPermissions) > 0 {
			for _, v := range chartPermissions {
				permissionMap[v.ClassifyId] = append(permissionMap[v.ClassifyId], v.ChartPermissionId)
				//permissionImageMap[v.KeyWord] = chartPermissionImageMap[v.ChartPermissionId]
			}
		}

		//获取二级分类的所有头像
		classifyList, tErr := classify.GetListByPid(classifyIdFirst)
		if tErr != nil {
			errMsg = tErr.Error()
			err = errors.New("二级分类查询出错")
			return
		}

		// 子目录
		if menuClassifyLen > 0 {
			classifyIdSeconds = append(classifyIdSeconds, menuClassifyIds...)
		} else {
			for _, v := range classifyList {
				classifyIdSeconds = append(classifyIdSeconds, v.Id)
			}
		}

		if len(classifyIdSeconds) == 0 && classifyParent.ClassifyName != "晨报" && classifyParent.ClassifyName != "周报" {
			ret = new(response.ReportList)
			ret.Paging = response.GetPaging(pageIndex, pageSize, 0)
			return
		}
		condition += ` AND classify_id_second IN ? `
		pars = append(pars, classifyIdSeconds)
	}

	// 获取有效的权限id列表
	var validPermissionIdList []int
	if productAuthOk {
		validPermissionIdList, err = company.GetValidPermissionIdListByCompany2ProductId(user.CompanyID, 1)
		if err != nil && err != utils.ErrNoRow {
			errMsg = err.Error()
			err = errors.New("查询分类出错")
			return
		}
	}

	if len(validPermissionIdList) > 0 {
		for cid, perIds := range permissionMap {
		checkLoop:
			for _, checkId := range perIds {
				for _, validPerid := range validPermissionIdList {
					if checkId == validPerid {
						checkPermissionMap[cid] = true
						break checkLoop
					}
				}
			}
		}
	}

	var total int64
	var list []*report.Report
	if keyWord == "" {
		offset := (pageIndex - 1) * pageSize
		list, err = report.GetReportList(condition, pars, offset, pageSize)
		if err != nil {
			errMsg = err.Error()
			err = errors.New("报告查询出错")
			return
		}
		total, err = report.GetReportListCount(condition, pars)
		if err != nil {
			errMsg = err.Error()
			err = errors.New("查询报告总数出错")
			return
		}
	} else {
		if classifyIdSecond > 0 {
			classifyIdSeconds = append(classifyIdSeconds, classifyIdSecond)
		}
		if classifyParent.ClassifyName == "晨报" || classifyParent.ClassifyName == "周报" {
			classifyIdSeconds = append(classifyIdSeconds, 0)
		}
		// 子目录
		if menuClassifyLen > 0 {
			classifyIdSeconds = append(classifyIdSeconds, menuClassifyIds...)
		}

		searchResp, total1, tErr := elasticService.ReportListSearch(keyWord, classifyIdFirst, classifyIdSeconds, pageIndex, pageSize)
		if tErr != nil {
			errMsg = tErr.Error()
			err = errors.New("查询失败")
			return
		}
		total = int64(total1)
		if searchResp.Hits != nil && total > 0 {
			var reportIds []int
			for _, v := range searchResp.Hits.Hits {
				temp := new(report.Report)
				itemJson, tmpErr := v.Source.MarshalJSON()
				if tmpErr != nil {
					errMsg = tmpErr.Error()
					err = errors.New("解析出错")
					return
				}
				reportItem := new(response.EsReportItem)
				tmpErr = json.Unmarshal(itemJson, &reportItem)
				if tmpErr != nil {
					errMsg = tmpErr.Error()
					err = errors.New("解析json出错")
					return
				}
				temp.Id = reportItem.ReportId
				reportIds = append(reportIds, reportItem.ReportId)
				temp.ClassifyIdFirst = reportItem.ClassifyIdFirst
				temp.ClassifyNameFirst = reportItem.ClassifyNameFirst
				temp.ClassifyIdSecond = reportItem.ClassifyIdSecond
				temp.ClassifyNameSecond = reportItem.ClassifyNameSecond
				if reportItem.ClassifyIdSecond > 0 && reportItem.ClassifyIdSecond != reportItem.ClassifyId {
					temp.ClassifyIdThird = reportItem.ClassifyId
					temp.ClassifyNameThird = reportItem.ClassifyName
				}
				if len(v.Highlight["ClassifyNameSecond"]) > 0 {
					temp.ClassifyNameSecond = v.Highlight["ClassifyNameSecond"][0]
				}
				temp.Abstract = reportItem.Abstract
				stageInt, _ := strconv.Atoi(reportItem.StageStr)
				temp.Stage = stageInt
				temp.StageStr = reportItem.StageStr
				temp.Title = reportItem.Title
				temp.PublishTime, err = time.ParseInLocation(utils.FormatDateTime, reportItem.PublishTime, time.Local)
				if len(v.Highlight["Title"]) > 0 {
					temp.Title = v.Highlight["Title"][0]
				}
				if len(v.Highlight["Abstract"]) > 0 {
					temp.Abstract = v.Highlight["Abstract"][0]
				}
				if len(v.Highlight["StageStr"]) > 0 {
					temp.StageStr = v.Highlight["StageStr"][0]
				}
				list = append(list, temp)
			}
			reportInfoList, tmpErr := report.GetByReportIds(reportIds)
			if tmpErr != nil {
				errMsg = tmpErr.Error()
				err = errors.New("查询报告出错")
				return
			}
			reportListMap := make(map[int]*report.Report)
			for _, temp := range reportInfoList {
				reportListMap[temp.Id] = temp
			}
			for k, reportDetail := range list {
				if v, ok := reportListMap[reportDetail.Id]; ok {
					list[k].CreateTime = v.CreateTime
					list[k].RaiReportId = v.RaiReportId
				}
			}
		}
	}

	var reportList []*response.ReportListItem
	if len(list) > 0 {
		// 封面图
		classifyList, e := classify.GetClassifyList()
		if e != nil {
			err = errors.New("获取报告分类列表失败" + e.Error())
			return
		}
		listImgMap := make(map[int]string)
		classifyNameMap := make(map[int]string)
		classifyMap := make(map[int]*classify.Classify)
		classifyLen := len(classifyList)
		for i := 0; i < classifyLen; i++ {
			listImgMap[classifyList[i].Id] = classifyList[i].YbListImg
			classifyNameMap[classifyList[i].Id] = classifyList[i].ClassifyName
			classifyMap[classifyList[i].Id] = classifyList[i]
		}

		var videoReportIds []int
		videoMap := make(map[int][]*response.VideoListItem)
		weekAuthMap := make(map[int]bool)

		// 判断周报权限\查询章节报告的音频列表
		videoMap, weekAuthMap, errMsg, err = GetReportChapterVideoList(validPermissionIdList, classifyParent.ClassifyName, list, user.UserID)
		if err != nil {
			return
		}

		// 如果是晨报，那么就要过滤掉weekAuthMap的授权
		if classifyParent.ClassifyName == "晨报" && productAuthOk {
			weekAuthMap = map[int]bool{}
		} else {
			//查询所有权限typeID
			//如果存在可以查看的章节ID
			for _, reportInfo := range list {
				if reportInfo.HasChapter == 1 {
					videoReportIds = append(videoReportIds, reportInfo.Id)
				}
			}
		}
		// 以下分类图标特殊处理 =_=!
		//reportImgMap := map[string]string{
		//	"晨报": "report_list_chen.png",
		//	"周报": "report_list_zhou.png",
		//	"月报": "report_list_yue.png",
		//	"大事点评": "report_list_dashidianping.png",
		//	"会议纪要": "report_list_huiyijiyao.png",
		//	"年报合集": "report_list_nianbaoheji.png",
		//}
		for _, reportInfo := range list {
			reportItem := new(response.ReportListItem)
			reportItem.ReportId = reportInfo.Id
			reportItem.HasChapter = reportInfo.HasChapter
			reportItem.VideoUrl = reportInfo.VideoUrl
			reportItem.VideoName = reportInfo.VideoName
			reportItem.VideoPlaySeconds = reportInfo.VideoPlaySeconds
			// 样式限制行数
			reportItem.Title = "<div style=\"-webkit-line-clamp: 2;-webkit-box-orient: vertical;display: -webkit-box;overflow: hidden;text-overflow: ellipsis;\">" + reportInfo.Title + "</div>"
			reportItem.PublishTime = reportInfo.PublishTime
			//reportItem.ClassifyNameFirst = reportInfo.ClassifyNameFirst
			//reportItem.ClassifyNameSecond = reportInfo.ClassifyNameSecond
			reportItem.ClassifyNameFirst = classifyNameMap[reportInfo.ClassifyIdFirst]
			reportItem.ClassifyNameSecond = classifyNameMap[reportInfo.ClassifyIdSecond]
			reportItem.ClassifyIdFirst = reportInfo.ClassifyIdFirst
			reportItem.ClassifyIdSecond = reportInfo.ClassifyIdSecond
			reportItem.ClassifyIdThird = reportInfo.ClassifyIdThird
			reportItem.ClassifyNameThird = reportInfo.ClassifyNameThird
			reportItem.Stage = reportInfo.Stage
			reportItem.Abstract = reportInfo.Abstract
			if reportInfo.Abstract != "" {
				reportItem.Abstract = "<div style=\"display: -webkit-box;overflow: hidden;text-overflow: ellipsis;word-break: break-all;-webkit-box-orient: vertical;-webkit-line-clamp: 1;\">" + reportInfo.Abstract + "</div>"
			}
			reportItem.Author = reportInfo.Author
			stageStr := reportInfo.StageStr
			if stageStr == "" {
				stageStr = strconv.Itoa(reportInfo.Stage)
			}
			reportItem.TitleInfo = fmt.Sprintf("【第%s期|FICC|%s】", stageStr, reportItem.ClassifyNameSecond)
			if reportItem.ClassifyNameThird != `` {
				reportItem.TitleInfo = fmt.Sprintf("%s|%s】", reportItem.TitleInfo, reportItem.ClassifyNameThird)
			}
			//trimClassifyNameSecond := utils.TrimHtml(reportInfo.ClassifyNameSecond)
			if reportItem.ClassifyNameFirst == "晨报" || reportItem.ClassifyNameFirst == "周报" || classifyIdSecond > 0 {
				//reportItem.ReportImgUrl = utils.ALIYUN_YBIMG_HOST + reportImgUrl
				reportItem.TitleInfo = fmt.Sprintf("【第%s期|FICC|%s】", stageStr, reportItem.ClassifyNameFirst)
			}
			reportItem.RaiReportId = reportInfo.RaiReportId
			if reportItem.RaiReportId > 0 {
				reportItem.TitleInfo = fmt.Sprintf("【FICC|%s】", reportItem.ClassifyNameFirst)
			}
			//else if url, ok := permissionImageMap[trimClassifyNameSecond]; ok {
			//	reportItem.ReportImgUrl = utils.ALIYUN_YBIMG_HOST + url
			//}
			//if img, ok := reportImgMap[reportInfo.ClassifyNameFirst]; ok {
			//	reportItem.ReportImgUrl = utils.ALIYUN_YBIMG_HOST + img
			//}
			// 封面图-默认取二级分类的图片,二级分类图片没有(如晨周报)则取一级
			coverImg := listImgMap[reportInfo.ClassifyIdSecond]
			if coverImg == "" {
				coverImg = listImgMap[reportInfo.ClassifyIdFirst]
			}
			reportItem.ReportImgUrl = coverImg
			reportItem.VideoImg = reportItem.ReportImgUrl
			
			if reportItem.HasChapter == 1 {
				if classifyParent.ClassifyName == "晨报" && productAuthOk {
					// 查询当前晨报的所有音频
					if vList, ok := videoMap[reportInfo.Id]; ok {
						for _, vd := range vList {
							vd.VideoImg = reportItem.ReportImgUrl
						}
						reportItem.VideoList = vList
					}
					reportItem.AuthOk = productAuthOk
				} else {
					if wAuth, ok := weekAuthMap[reportInfo.Id]; ok {
						reportItem.AuthOk = wAuth
						if wAuth {
							// 查询当前晨报的所有音频
							if vList, ok2 := videoMap[reportInfo.Id]; ok2 {
								for _, vd := range vList {
									vd.VideoImg = reportItem.ReportImgUrl
								}
								reportItem.VideoList = vList
							}
						}
					}
				}
			} else if authOk, ok := checkPermissionMap[reportInfo.ClassifyIdSecond]; ok && authOk {
				if reportInfo.VideoUrl != "" {
					videoTemp := new(response.VideoListItem)
					videoTemp.VideoUrl = reportInfo.VideoUrl
					videoTemp.VideoName = reportInfo.VideoName
					if reportInfo.VideoName == "" {
						videoTemp.VideoName = reportInfo.Title
					}
					videoTemp.VideoPlaySeconds = reportInfo.VideoPlaySeconds
					videoTemp.VideoImg = reportItem.ReportImgUrl
					reportItem.VideoList = append(reportItem.VideoList, videoTemp)
				}
				reportItem.AuthOk = authOk
			}

			// 报告详情展示形式
			{
				minClassifyId := reportItem.ClassifyIdThird
				if minClassifyId <= 0 {
					minClassifyId = reportItem.ClassifyIdSecond
				}
				if minClassifyId <= 0 {
					minClassifyId = reportItem.ClassifyIdFirst
				}
				if tmpClassify, ok := classifyMap[minClassifyId]; ok {
					reportItem.ReportDetailShowType = int(tmpClassify.ReportDetailShowType)
				}
			}

			reportList = append(reportList, reportItem)
		}

	}
	ret = new(response.ReportList)
	ret.List = reportList
	ret.Paging = response.GetPaging(pageIndex, pageSize, int(total))
	return
}

// GetCollectReportList 首页展示报告汇总列表
func GetCollectReportList(user user.UserInfo, chartPermissionId, pageIndex, pageSize int) (ret *response.ReportCollectResp, err error) {
	var errMsg string
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("GetCollectReportList: userId=%d, err:%s， errMsg:%s", user.UserID, err.Error(), errMsg))
		}
	}()

	// 查询权限的基本信息
	permissionInfo, err := chart_permission.GetByChartPermissionId(chartPermissionId)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询权限出错")
		return
	}

	if permissionInfo.ChartPermissionID == 0 {
		err = errors.New("权限不存在")
		return
	}
	// 除了晨报和周报以外的其他报告
	classifyIdList, err := chart_permission_search_key_word_mapping.GetClassifyIdsByChartPermissionId(chartPermissionId, "rddp")
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询权限对应的分类出错")
		return
	}

	var firstClassifyIdList, secondClassifyIdList, thirdClassifyIdList []int
	{
		classifyList, tmpErr := classify.GetListByClassifyIdList(classifyIdList)
		if tmpErr != nil {
			errMsg = tmpErr.Error()
			err = errors.New("查询分类信息失败")
			return
		}

		for _, v := range classifyList {
			switch v.Level {
			case 1:
				firstClassifyIdList = append(firstClassifyIdList, v.Id)
			case 2:
				secondClassifyIdList = append(secondClassifyIdList, v.Id)
			case 3:
				thirdClassifyIdList = append(thirdClassifyIdList, v.Id)
			}
		}
	}

	var reportList []*response.ReportCollectListItem
	list := response.ReportCollectListResp{}
	var total int64

	{
		offset := (pageIndex - 1) * pageSize
		reportList, err = report.GetReportCollectListByPermissionV1(chartPermissionId, firstClassifyIdList, secondClassifyIdList, thirdClassifyIdList, offset, pageSize)
		if err != nil {
			errMsg = err.Error()
			err = errors.New("查询报告信息出错")
			return
		}
		listMap := make(map[string]*response.ReportCollectList)
		for _, v := range reportList {
			v.ContentSub = GetReportContentSub(v.ContentSub, true)
			if _, ok := listMap[v.PublishTime.Format("2006-01-02")]; !ok {
				temp := new(response.ReportCollectList)
				temp.Date = v.PublishTime.Format("2006-01-02")
				listMap[v.PublishTime.Format("2006-01-02")] = temp
			}
			listMap[v.PublishTime.Format("2006-01-02")].SubList = append(listMap[v.PublishTime.Format("2006-01-02")].SubList, v)
		}
		for _, v := range listMap {
			list = append(list, v)
		}
		total, err = report.GetReportCollectCountByPermissionV1(chartPermissionId, classifyIdList)
		if err != nil {
			errMsg = err.Error()
			err = errors.New("查询报告总数出错")
			return
		}
		if len(list) > 0 {
			sort.Sort(list)
		}
	}

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

func GetCollectReportListBak(user user.UserInfo, chartPermissionId, pageIndex, pageSize int) (ret *response.ReportCollectResp, err error) {
	var errMsg string
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("GetCollectReportList: userId=%d, err:%s， errMsg:%s", user.UserID, err.Error(), errMsg))
		}
	}()

	// 查询权限的基本信息
	permissionInfo, err := chart_permission.GetByChartPermissionId(chartPermissionId)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询权限出错")
		return
	}

	if permissionInfo.ChartPermissionID == 0 {
		err = errors.New("权限不存在")
		return
	}
	// 除了晨报和周报以外的其他报告
	classifySecondIds, err := chart_permission_search_key_word_mapping.GetClassifyIdsByChartPermissionId(chartPermissionId, "rddp")
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询权限对应的分类出错")
		return
	}

	//var classifySecondIds []int
	//if len(classifyNames) > 0 {
	//	classifySecondIds, err = classify.GetSecondIdsByClassifyNames(classifyNames)
	//	if err != nil {
	//		errMsg = err.Error()
	//		err = errors.New("查询分类出错")
	//		return
	//	}
	//}

	// 查询晨报和周报相对应的章节ID
	reportChapterTypeIds, err := report_chapter_type_permission.GetTypeIdsByChartPermissionId(chartPermissionId)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询权限对应的章节出错")
		return
	}

	var reportList []*response.ReportCollectListItem
	list := response.ReportCollectListResp{}
	var total int64
	if len(reportChapterTypeIds) > 0 || len(classifySecondIds) > 0 {
		offset := (pageIndex - 1) * pageSize
		reportList, err = report.GetReportCollectListByPermission(classifySecondIds, reportChapterTypeIds, offset, pageSize)
		if err != nil {
			errMsg = err.Error()
			err = errors.New("查询报告信息出错")
			return
		}
		listMap := make(map[string]*response.ReportCollectList)
		for _, v := range reportList {
			v.ContentSub = GetReportContentSub(v.ContentSub, true)
			if _, ok := listMap[v.PublishTime.Format("2006-01-02")]; !ok {
				temp := new(response.ReportCollectList)
				temp.Date = v.PublishTime.Format("2006-01-02")
				listMap[v.PublishTime.Format("2006-01-02")] = temp
			}
			listMap[v.PublishTime.Format("2006-01-02")].SubList = append(listMap[v.PublishTime.Format("2006-01-02")].SubList, v)
		}
		for _, v := range listMap {
			list = append(list, v)
		}
		total, err = report.GetReportCollectCountByPermission(classifySecondIds, reportChapterTypeIds)
		if err != nil {
			errMsg = err.Error()
			err = errors.New("查询报告总数出错")
			return
		}
		if len(list) > 0 {
			sort.Sort(list)
		}
	}

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

func SearchReport(user user.UserInfo, keyWord string, pageIndex, pageSize int) (ret *response.ReportSearchResp, err error) {
	var errMsg string
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("SearchReport: userId=%d, err:%s， errMsg:%s", user.UserID, err.Error(), errMsg))
		}
	}()
	//查询正常状态的分类
	classifys, err := classify.GetSimpleAll()
	if err != nil {
		errMsg = err.Error()
		err = errors.New("分类查询出错")
		return
	}
	classifyIdList := make([]int, 0)
	var classifyIdFirsts []int
	classifyIdSeconds := []int{0}
	classifyMap := make(map[int]*classify.Classify)
	for _, v := range classifys {
		if v.ParentId == 0 {
			classifyIdFirsts = append(classifyIdFirsts, v.Id)
		} else {
			classifyIdSeconds = append(classifyIdSeconds, v.Id)
		}
		classifyIdList = append(classifyIdList, v.Id)
		classifyMap[v.Id] = v
	}
	keyWord = addAliasToKeyword(keyWord)
	searchResp, total, err := elasticService.SearchReport(keyWord, classifyIdList, pageIndex, pageSize)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询失败")
		return
	}
	var reportList []*response.ReportCollectListItem
	if searchResp.Hits != nil {
		reportIds := make([]int, 0)
		for _, v := range searchResp.Hits.Hits {
			temp := new(response.ReportCollectListItem)
			itemJson, tmpErr := v.Source.MarshalJSON()
			if tmpErr != nil {
				errMsg = tmpErr.Error()
				err = errors.New("解析出错")
				return
			}
			reportItem := new(response.EsReportItem)
			tmpErr = json.Unmarshal(itemJson, &reportItem)
			if tmpErr != nil {
				errMsg = tmpErr.Error()
				err = errors.New("解析json出错")
				return
			}
			reportIds = append(reportIds, reportItem.ReportId)
			temp.ReportId = reportItem.ReportId
			temp.ReportChapterId = reportItem.ReportChapterId
			temp.ClassifyIdFirst = reportItem.ClassifyIdFirst
			temp.ClassifyNameFirst = reportItem.ClassifyNameFirst
			temp.ClassifyIdSecond = reportItem.ClassifyIdSecond
			temp.ClassifyNameSecond = reportItem.ClassifyNameSecond
			temp.ClassifyId = reportItem.ClassifyId
			temp.ClassifyName = reportItem.ClassifyName
			temp.Title = reportItem.Title
			temp.ContentSub = reportItem.BodyContent
			temp.PublishTime, err = time.ParseInLocation(utils.FormatDateTime, reportItem.PublishTime, time.Local)

			if len(v.Highlight["Title"]) > 0 {
				temp.Title = v.Highlight["Title"][0]
			}
			if len(v.Highlight["BodyContent"]) > 0 {
				temp.ContentSub = v.Highlight["BodyContent"][0]
			}
			//if len(v.Highlight["Categories"]) > 0 {
			//	if temp.ClassifyNameSecond != "" {
			//		temp.ClassifyNameSecond = "<span style=\"color:#E3B377\">"+temp.ClassifyNameSecond+"</span>"
			//	}
			//	if temp.ClassifyNameFirst != "" {
			//		temp.ClassifyNameFirst = "<span style=\"color:#E3B377\">"+temp.ClassifyNameFirst+"</span>"
			//	}
			//}
			temp.ContentSub = GetReportContentSub(temp.ContentSub, false)

			if tmpClassify, ok := classifyMap[temp.ClassifyId]; ok {
				temp.ReportDetailShowType = int(tmpClassify.ReportDetailShowType)
			}
			reportList = append(reportList, temp)
		}

		reportInfoList, tmpErr := report.GetByReportIds(reportIds)
		if tmpErr != nil {
			errMsg = tmpErr.Error()
			err = errors.New("查询报告出错")
			return
		}
		reportListMap := make(map[int]*report.Report)
		for _, temp := range reportInfoList {
			reportListMap[temp.Id] = temp
		}
		for _, reportDetail := range reportList {
			if v, ok := reportListMap[reportDetail.ReportId]; ok {
				reportDetail.RaiReportId = v.RaiReportId
			}
		}
	}
	ret = new(response.ReportSearchResp)
	ret.List = reportList
	ret.Paging = response.GetPaging(pageIndex, pageSize, int(total))
	return
}

// GetTickerData 获取指标数据
func GetTickerData(user user.UserInfo, reportChapterId int) (ret *response.TickerData, err error) {
	var errMsg string
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("GetTickerData: userId=%d, err:%s， errMsg:%s", user.UserID, err.Error(), errMsg))
		}
	}()

	//查询章节类型
	chapter, err := report_chapter.GetTypeIdById(reportChapterId)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询章节失败")
		return
	}

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

	tickers, err := report_chapter_ticker.GetTickerByChapterId(reportChapterId)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询章节指标失败")
		return
	}

	var list []*response.TickerDataItem
	if len(tickers) > 0 {
		var tickerNames []string
		for _, v := range tickers {
			tickerNames = append(tickerNames, v.Ticker)
		}
		var dataList []*response.TickerDataItem
		if chapter.TypeId == 17 {
			dataList, err = daily_base_column.GetDataByBaseColumnTickers17(tickerNames)
		} else {
			dataList, err = daily_base_column.GetDataByBaseColumnTickers(tickerNames)
		}

		if err != nil {
			errMsg = err.Error()
			err = errors.New("查询指标数据失败")
			return
		}
		chapterTypeInfo, tErr := report_chapter_type.GetTickerTitleByTypeId(chapter.TypeId)
		if tErr != nil {
			errMsg = tErr.Error()
			err = errors.New("查询章节类型失败")
			return
		}
		if len(dataList) >= 0 {
			for _, v := range dataList {
				temp := new(response.TickerDataItem)
				temp.BaseColumnName = v.BaseColumnName
				temp.Ticker = v.Ticker
				temp.Date = v.Date
				temp.TickerValue, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", v.TickerValue), 2)
				temp.LastValue, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", v.LastValue), 2)
				temp.MmValue, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", v.MmValue), 2)
				temp.DdValue, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", v.DdValue), 2)
				temp.WwValue, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", v.WwValue), 2)

				list = append(list, temp)
			}
		}

		tickerTitle := new(response.TickerTitleData)
		tickerTitle.TickerTitle = chapterTypeInfo.TickerTitle
		tickerTitle.ReportChapterTypeId = int(chapterTypeInfo.ReportChapterTypeId)
		tickerTitle.ReportChapterTypeName = chapterTypeInfo.ReportChapterTypeName
		tickerTitle.DataTableImage = fmt.Sprintf("http://hongze.oss-cn-shanghai.aliyuncs.com/data_table/%s.png", chapterTypeInfo.ReportChapterTypeKey)

		ret = new(response.TickerData)
		ret.List = list
		ret.TickerTitle = tickerTitle
	}
	return
}

// GetReportContentSub 特殊处理contentSub
func GetReportContentSub(content string, scapeFlag bool) (contentSub string) {
	if scapeFlag {
		content = html.UnescapeString(content)
		content = utils.TrimHtml(content) //只展示纯文本
	}
	contentSub = "<div style=\"-webkit-line-clamp: 3;-webkit-box-orient: vertical;display: -webkit-box;overflow: hidden;text-overflow: ellipsis;\">" + content + "</div>"
	return
}

// addAliasToKeyword 品种别名
func addAliasToKeyword(keyword string) string {
	if keyword == "" {
		return ""
	}
	keywordArr := make([]string, 0)
	keywordArr = append(keywordArr, keyword)
	if strings.Contains(keyword, "沥青") || strings.Contains(keyword, "BU") {
		keywordArr = append(keywordArr, "沥青", "BU")
	}
	if strings.Contains(keyword, "MEG") || strings.Contains(keyword, "EG") || strings.Contains(keyword, "乙二醇") {
		keywordArr = append(keywordArr, "MEG", "EG", "乙二醇")
	}
	if strings.Contains(keyword, "聚酯") || strings.Contains(keyword, "长丝") || strings.Contains(keyword, "短纤") || strings.Contains(keyword, "瓶片") {
		keywordArr = append(keywordArr, "聚酯", "长丝", "短纤", "瓶片")
	}
	if strings.Contains(keyword, "纯苯") || strings.Contains(keyword, "苯乙烯") || strings.Contains(keyword, "EB") {
		keywordArr = append(keywordArr, "纯苯", "苯乙烯", "EB")
	}
	if strings.Contains(keyword, "甲醇") || strings.Contains(keyword, "MA") {
		keywordArr = append(keywordArr, "甲醇", "MA")
	}
	if strings.Contains(keyword, "橡胶") || strings.Contains(keyword, "RU") {
		keywordArr = append(keywordArr, "橡胶", "RU")
	}
	if strings.Contains(keyword, "聚乙烯") || strings.Contains(keyword, "PP") || strings.Contains(keyword, "PE") {
		keywordArr = append(keywordArr, "聚乙烯", "PP", "PE")
	}
	if strings.Contains(keyword, "玻璃") || strings.Contains(keyword, "纯碱") || strings.Contains(keyword, "FG") || strings.Contains(keyword, "SA") {
		keywordArr = append(keywordArr, "玻璃", "纯碱", "FG", "SA")
	}
	keyword = strings.Join(keywordArr, ",")
	return keyword
}

// GetReportPptImgListByReportIdAndReportChapterId 首页展示报告汇总列表
func GetReportPptImgListByReportIdAndReportChapterId(reportId, reportChapterId int) (list []string, err error) {
	list = make([]string, 0)
	reportPptImgList, err := report_ppt_img.GetReportPptImgListByReportIdAndReportChapterId(reportId, reportChapterId)

	for _, v := range reportPptImgList {
		list = append(list, v.ImgURL)
	}

	return
}

// GetVarietyReportList 大宗商品报告列表
func GetVarietyReportList(user user.UserInfo, classifyId, chartPermissionId, pageIndex, pageSize int) (ret *response.ReportList, err error) {
	var errMsg string
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("GetCollectReportList: userId=%d, err:%s， errMsg:%s", user.UserID, err.Error(), errMsg))
		}
	}()

	// 判断用户状态是否是正常和永续
	var productAuthOk bool
	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
			}
		}
	}

	// 查询权限的基本信息
	permissionInfo, err := chart_permission.GetByChartPermissionId(chartPermissionId)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询权限出错")
		return
	}

	if permissionInfo.ChartPermissionID == 0 {
		err = errors.New("权限不存在")
		return
	}

	//分类ids
	var allClassifySecondIds []int
	var classifySecondIds []int

	allClassifySecondIds, err = chart_permission_search_key_word_mapping.GetClassifyIdsByChartPermissionId(chartPermissionId, "rddp")
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询权限对应的分类出错")
		return
	}

	//if len(classifyNames) > 0 {
	//	allClassifySecondIds, err = classify.GetSecondIdsByClassifyNames(classifyNames)
	//	if err != nil {
	//		errMsg = err.Error()
	//		err = errors.New("查询分类出错")
	//		return
	//	}
	//}

	//根据所选一级分类id查询二级分类
	classifyChild, err := classify.GetChildByPid(classifyId)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询二级分类出错")
		return
	}
	classifyMap := make(map[int]int, 0)
	for _, c := range classifyChild {
		classifyMap[c.Id] = c.Id
	}

	for _, id := range allClassifySecondIds {
		if _, ok := classifyMap[id]; ok {
			classifySecondIds = append(classifySecondIds, id)
		}
	}

	listImgMap := make(map[int]string, 0)
	for i := 0; i < len(classifyChild); i++ {
		listImgMap[classifyChild[i].Id] = classifyChild[i].YbListImg
	}

	// 获取有效的权限id列表
	var validPermissionIdList []int
	if productAuthOk {
		validPermissionIdList, err = company.GetValidPermissionIdListByCompany2ProductId(user.CompanyID, 1)
		if err != nil && err != utils.ErrNoRow {
			errMsg = err.Error()
			err = errors.New("查询分类出错")
			return
		}
	}
	var authOk bool
	if len(validPermissionIdList) > 0 {
	checkLoop:
		for _, validPerid := range validPermissionIdList {
			if chartPermissionId == validPerid {
				authOk = true
				break checkLoop
			}
		}
	}
	//// 查询晨报和周报相对应的章节ID
	//reportChapterTypeIds, err := report_chapter_type_permission.GetTypeIdsByChartPermissionId(chartPermissionId)
	//if err != nil {
	//	errMsg = err.Error()
	//	err = errors.New("查询权限对应的章节出错")
	//	return
	//}

	var reportList []*report.Report
	var total int64
	if len(classifySecondIds) > 0 {
		if productAuthOk {
			offset := (pageIndex - 1) * pageSize
			reportList, err = report.GetCommoditiesReportCollectListByPermission(classifySecondIds, offset, pageSize)
			if err != nil {
				errMsg = err.Error()
				err = errors.New("查询报告信息出错")
				return
			}

			total, err = report.GetCommoditiesReportCollectCountByPermission(classifySecondIds)
			if err != nil {
				errMsg = err.Error()
				err = errors.New("查询报告总数出错")
				return
			}
		}
	}
	var list []*response.ReportListItem
	for _, r := range reportList {
		// 封面图-默认取二级分类的图片,二级分类图片没有(如晨周报)则取一级
		coverImg := listImgMap[r.ClassifyIdSecond]
		if coverImg == "" {
			coverImg = listImgMap[r.ClassifyIdFirst]
		}
		var VideoList []*response.VideoListItem
		videoItem := response.VideoListItem{
			VideoUrl:         r.VideoUrl,
			VideoName:        r.VideoName,
			VideoPlaySeconds: r.VideoPlaySeconds,
			VideoImg:         coverImg,
		}
		VideoList = append(VideoList, &videoItem)
		stageStr := r.StageStr
		if stageStr == "" {
			stageStr = strconv.Itoa(r.Stage)
		}
		item := response.ReportListItem{
			ReportId:           r.Id,
			ClassifyIdFirst:    r.ClassifyIdFirst,
			ClassifyNameFirst:  r.ClassifyNameFirst,
			ClassifyIdSecond:   r.ClassifyIdSecond,
			ClassifyNameSecond: r.ClassifyNameSecond,
			Title:              r.Title,
			Abstract:           r.Abstract,
			Author:             r.Author,
			ReportImgUrl:       coverImg,
			PublishTime:        r.PublishTime,
			Stage:              r.Stage,
			VideoList:          VideoList,
			AuthOk:             authOk,
			TitleInfo:          fmt.Sprintf("【第%s期|FICC|%s】", stageStr, r.ClassifyNameSecond),
		}
		list = append(list, &item)
	}
	ret = new(response.ReportList)
	ret.List = list
	ret.Paging = response.GetPaging(pageIndex, pageSize, int(total))
	return
}

// GetMinClassify
// @Description: 获取最小分类ID
// @author: Roc
// @datetime 2024-06-20 09:23:19
// @param reportInfo *models.Report
// @return minClassifyId int
// @return minClassifyName string
// @return err error
func GetMinClassify(reportInfo *report.Report) (minClassifyId int, minClassifyName string, err error) {
	defer func() {
		if err != nil {
			global.FILE_LOG.Error("获取最小分类ID失败，报告ID：%d，Err：%s", reportInfo.Id, err.Error())
		}
	}()
	minClassifyId = reportInfo.ClassifyIdThird
	minClassifyName = reportInfo.ClassifyNameThird
	if minClassifyId <= 0 {
		minClassifyId = reportInfo.ClassifyIdSecond
		minClassifyName = reportInfo.ClassifyNameSecond
	}
	if minClassifyId <= 0 {
		minClassifyId = reportInfo.ClassifyIdFirst
		minClassifyName = reportInfo.ClassifyNameFirst
	}
	if minClassifyId <= 0 {
		err = errors.New("分类异常")
	}

	return
}

// GetCommoditiesReportList 获取大宗商品报告列表
//func GetCommoditiesReportList(user user.UserInfo, chartPermissionId, pageIndex, pageSize int) (ret *response.ReportList, err error) {
//	var errMsg string
//	defer func() {
//		if err != nil {
//			global.LOG.Critical(fmt.Sprintf("GetReportList: userId=%d, err:%s， errMsg:%s", user.UserID, err.Error(), errMsg))
//		}
//	}()
//
//	// 判断用户状态是否是正常和永续
//	var productAuthOk bool
//	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
//			}
//		}
//	}
//
//	// 查询权限的基本信息
//	permissionInfo, err := chart_permission.GetByChartPermissionId(chartPermissionId)
//	if err != nil {
//		errMsg = err.Error()
//		err = errors.New("查询权限出错")
//		return
//	}
//
//	if permissionInfo.ChartPermissionID == 0 {
//		err = errors.New("权限不存在")
//		return
//	}
//	// 除了晨报和周报以外的其他报告
//	classifyNames, err := chart_permission_search_key_word_mapping.GetClassifyIdsByChartPermissionId(chartPermissionId, "two_week")
//	if err != nil {
//		errMsg = err.Error()
//		err = errors.New("查询权限对应的分类出错")
//		return
//	}
//
//	var classifySecondIds []int
//	if len(classifyNames) > 0 {
//		classifySecondIds, err = classify.GetSecondIdsByClassifyNames(classifyNames)
//		if err != nil {
//			errMsg = err.Error()
//			err = errors.New("查询分类出错")
//			return
//		}
//	}
//
//	var condition string
//	pars := make([]interface{}, 0)
//
//	classifyParent, err := classify.GetByClassifyId(classifyIdFirst)
//	if err != nil {
//		errMsg = err.Error()
//		err = errors.New("分类查询出错")
//		return
//	}
//	if classifyParent.Id == 0 {
//		err = errors.New("该分类不存在")
//		return
//	}
//	condition = `classify_id_first = ? and state IN (2, 6)`
//	pars = append(pars, classifyIdFirst)
//	permissionMap := make(map[string][]int)
//	checkPermissionMap := make(map[string]bool)
//	permissionImageMap := make(map[string]string)
//	chartPermissionImageMap := make(map[int]string)
//	var classifyIdSeconds []int
//	//var reportImgUrl string
//
//	chartPermissionList, err := chart_permission.GetFiccListExceptTacticByProductId()
//	if err != nil {
//		errMsg = err.Error()
//		err = errors.New("分类查询出错")
//		return
//	}
//
//	if len(chartPermissionList) > 0 {
//		for _, v := range chartPermissionList {
//			chartPermissionImageMap[int(v.ChartPermissionID)] = v.YbImgUrl
//		}
//	}
//
//	if classifyIdSecond > 0 && keyWord == "" {
//		classifyInfo, tErr := classify.GetByClassifyId(classifyIdSecond)
//		if tErr != nil {
//			errMsg = tErr.Error()
//			err = errors.New("分类查询出错")
//			return
//		}
//		if classifyInfo.Id == 0 {
//			err = errors.New("该二级分类不存在")
//			return
//		}
//
//		condition += " AND classify_id_second = ?"
//		pars = append(pars, classifyIdSecond)
//		//查询二级分类对应的权限
//		permissionIds, tErr := chart_permission_search_key_word_mapping.GetChartPermissionIdsByKeyWord(classifyInfo.ClassifyName)
//		if tErr != nil {
//			errMsg = tErr.Error()
//			err = errors.New("分类权限查询出错")
//			return
//		}
//		permissionMap[classifyInfo.ClassifyName] = permissionIds
//		//if len(permissionIds) > 0 {
//		//	for _, v := range permissionIds {
//		//		reportImgUrl = chartPermissionImageMap[v]
//		//	}
//		//}
//
//	} else {
//		if classifyParent.ClassifyName == "晨报" || classifyParent.ClassifyName == "周报" {
//			//reportImgUrl = chartPermissionImageMap[1]
//			classifyIdSeconds = append(classifyIdSeconds, 0)
//		}
//
//		chartPermissions, tErr := chart_permission_search_key_word_mapping.GetChartPermissionByFrom("rddp")
//		if tErr != nil {
//			errMsg = tErr.Error()
//			err = errors.New("分类权限查询出错")
//			return
//		}
//
//		if len(chartPermissions) > 0 {
//			for _, v := range chartPermissions {
//				permissionMap[v.KeyWord] = append(permissionMap[v.KeyWord], v.ChartPermissionId)
//				permissionImageMap[v.KeyWord] = chartPermissionImageMap[v.ChartPermissionId]
//			}
//		}
//
//		//获取二级分类的所有头像
//		classifyList, tErr := classify.GetListByPid(classifyIdFirst)
//		if tErr != nil {
//			errMsg = tErr.Error()
//			err = errors.New("二级分类查询出错")
//			return
//		}
//
//		for _, v := range classifyList {
//			classifyIdSeconds = append(classifyIdSeconds, v.Id)
//		}
//
//		if len(classifyIdSeconds) == 0 && classifyParent.ClassifyName != "晨报" && classifyParent.ClassifyName != "周报" {
//			ret = new(response.ReportList)
//			ret.Paging = response.GetPaging(pageIndex, pageSize, 0)
//			return
//		}
//		condition += ` AND classify_id_second IN ? `
//		pars = append(pars, classifyIdSeconds)
//	}
//
//	// 获取有效的权限id列表
//	var validPermissionIdList []int
//	if productAuthOk {
//		validPermissionIdList, err = company.GetValidPermissionIdListByCompany2ProductId(user.CompanyID, 1)
//		if err != nil && err != utils.ErrNoRow {
//			errMsg = err.Error()
//			err = errors.New("查询分类出错")
//			return
//		}
//	}
//
//	if len(validPermissionIdList) > 0 {
//		for classifyName, perIds := range permissionMap {
//		checkLoop:
//			for _, checkId := range perIds {
//				for _, validPerid := range validPermissionIdList {
//					if checkId == validPerid {
//						checkPermissionMap[classifyName] = true
//						break checkLoop
//					}
//				}
//			}
//		}
//	}
//
//	var total int64
//	var list []*report.Report
//	if keyWord == "" {
//		offset := (pageIndex - 1) * pageSize
//		list, err = report.GetReportList(condition, pars, offset, pageSize)
//		if err != nil {
//			errMsg = err.Error()
//			err = errors.New("报告查询出错")
//			return
//		}
//		total, err = report.GetReportListCount(condition, pars)
//		if err != nil {
//			errMsg = err.Error()
//			err = errors.New("查询报告总数出错")
//			return
//		}
//	} else {
//		if classifyIdSecond > 0 {
//			classifyIdSeconds = append(classifyIdSeconds, classifyIdSecond)
//		}
//		if classifyParent.ClassifyName == "晨报" || classifyParent.ClassifyName == "周报" {
//			classifyIdSeconds = append(classifyIdSeconds, 0)
//		}
//		searchResp, total1, tErr := elasticService.ReportListSearch(keyWord, classifyIdFirst, classifyIdSeconds, pageIndex, pageSize)
//		if tErr != nil {
//			errMsg = tErr.Error()
//			err = errors.New("查询失败")
//			return
//		}
//		total = int64(total1)
//		if searchResp.Hits != nil && total > 0 {
//			var reportIds []int
//			for _, v := range searchResp.Hits.Hits {
//				temp := new(report.Report)
//				itemJson, tmpErr := v.Source.MarshalJSON()
//				if tmpErr != nil {
//					errMsg = tmpErr.Error()
//					err = errors.New("解析出错")
//					return
//				}
//				reportItem := new(response.EsReportItem)
//				tmpErr = json.Unmarshal(itemJson, &reportItem)
//				if tmpErr != nil {
//					errMsg = tmpErr.Error()
//					err = errors.New("解析json出错")
//					return
//				}
//				temp.Id = reportItem.ReportId
//				reportIds = append(reportIds, reportItem.ReportId)
//				temp.ClassifyIdFirst = reportItem.ClassifyIdFirst
//				temp.ClassifyNameFirst = reportItem.ClassifyNameFirst
//				temp.ClassifyIdSecond = reportItem.ClassifyIdSecond
//				temp.ClassifyNameSecond = reportItem.ClassifyNameSecond
//				if len(v.Highlight["ClassifyNameSecond"]) > 0 {
//					temp.ClassifyNameSecond = v.Highlight["ClassifyNameSecond"][0]
//				}
//				temp.Abstract = reportItem.Abstract
//				stageInt, _ := strconv.Atoi(reportItem.StageStr)
//				temp.Stage = stageInt
//				temp.StageStr = reportItem.StageStr
//				temp.Title = reportItem.Title
//				temp.PublishTime, err = time.ParseInLocation(utils.FormatDateTime, reportItem.PublishTime, time.Local)
//				if len(v.Highlight["Title"]) > 0 {
//					temp.Title = v.Highlight["Title"][0]
//				}
//				if len(v.Highlight["Abstract"]) > 0 {
//					temp.Abstract = v.Highlight["Abstract"][0]
//				}
//				if len(v.Highlight["StageStr"]) > 0 {
//					temp.StageStr = v.Highlight["StageStr"][0]
//				}
//				list = append(list, temp)
//			}
//			reportInfoList, tmpErr := report.GetByReportIds(reportIds)
//			if tmpErr != nil {
//				errMsg = tmpErr.Error()
//				err = errors.New("查询报告出错")
//				return
//			}
//			reportListMap := make(map[int]*report.Report)
//			for _, temp := range reportInfoList {
//				reportListMap[temp.Id] = temp
//			}
//			for k, reportDetail := range list {
//				if v, ok := reportListMap[reportDetail.Id]; ok {
//					list[k].CreateTime = v.CreateTime
//				}
//			}
//		}
//	}
//
//	var reportList []*response.ReportListItem
//	if len(list) > 0 {
//		// 封面图
//		classifyList, e := classify.GetClassifyList()
//		if e != nil {
//			err = errors.New("获取报告分类列表失败" + e.Error())
//			return
//		}
//		listImgMap := make(map[int]string, 0)
//		classifyLen := len(classifyList)
//		for i := 0; i < classifyLen; i++ {
//			listImgMap[classifyList[i].Id] = classifyList[i].YbListImg
//		}
//
//		var videoReportIds []int
//		videoMap := make(map[int][]*response.VideoListItem)
//		weekAuthMap := make(map[int]bool)
//		if classifyParent.ClassifyName == "晨报" && productAuthOk {
//			//获取晨报的音频列表
//			videoMap, _, errMsg, err = GetReportChapterVideoList(validPermissionIdList, classifyParent.ClassifyName, list)
//			if err != nil {
//				return
//			}
//		} else if classifyParent.ClassifyName == "周报" {
//			//查询所有权限typeID
//			//如果存在可以查看的章节ID
//			for _, reportInfo := range list {
//				videoReportIds = append(videoReportIds, reportInfo.Id)
//			}
//			// 判断周报权限\查询周报的音频列表
//			videoMap, weekAuthMap, errMsg, err = GetReportChapterVideoList(validPermissionIdList, classifyParent.ClassifyName, list)
//			if err != nil {
//				return
//			}
//		}
//		// 以下分类图标特殊处理 =_=!
//		//reportImgMap := map[string]string{
//		//	"晨报": "report_list_chen.png",
//		//	"周报": "report_list_zhou.png",
//		//	"月报": "report_list_yue.png",
//		//	"大事点评": "report_list_dashidianping.png",
//		//	"会议纪要": "report_list_huiyijiyao.png",
//		//	"年报合集": "report_list_nianbaoheji.png",
//		//}
//		for _, reportInfo := range list {
//			reportItem := new(response.ReportListItem)
//			reportItem.ReportId = reportInfo.Id
//			// 样式限制行数
//			reportItem.Title = "<div style=\"-webkit-line-clamp: 2;-webkit-box-orient: vertical;display: -webkit-box;overflow: hidden;text-overflow: ellipsis;\">" + reportInfo.Title + "</div>"
//			reportItem.PublishTime = reportInfo.PublishTime
//			reportItem.ClassifyNameFirst = reportInfo.ClassifyNameFirst
//			reportItem.ClassifyNameSecond = reportInfo.ClassifyNameSecond
//			reportItem.ClassifyIdFirst = reportInfo.ClassifyIdFirst
//			reportItem.ClassifyIdSecond = reportInfo.ClassifyIdSecond
//			reportItem.Stage = reportInfo.Stage
//			reportItem.Abstract = reportInfo.Abstract
//			if reportInfo.Abstract != "" {
//				reportItem.Abstract = "<div style=\"overflow: hidden;white-space: nowrap;text-overflow: ellipsis;\">" + reportInfo.Abstract + "</div>"
//			}
//			reportItem.Author = reportInfo.Author
//			stageStr := reportInfo.StageStr
//			if stageStr == "" {
//				stageStr = strconv.Itoa(reportInfo.Stage)
//			}
//			reportItem.TitleInfo = fmt.Sprintf("【第%s期|FICC|%s】", stageStr, reportItem.ClassifyNameSecond)
//			//trimClassifyNameSecond := utils.TrimHtml(reportInfo.ClassifyNameSecond)
//			if reportInfo.ClassifyNameFirst == "晨报" || reportInfo.ClassifyNameFirst == "周报" || classifyIdSecond > 0 {
//				//reportItem.ReportImgUrl = utils.ALIYUN_YBIMG_HOST + reportImgUrl
//				reportItem.TitleInfo = fmt.Sprintf("【第%s期|FICC|%s】", stageStr, reportItem.ClassifyNameFirst)
//			}
//			//else if url, ok := permissionImageMap[trimClassifyNameSecond]; ok {
//			//	reportItem.ReportImgUrl = utils.ALIYUN_YBIMG_HOST + url
//			//}
//			//if img, ok := reportImgMap[reportInfo.ClassifyNameFirst]; ok {
//			//	reportItem.ReportImgUrl = utils.ALIYUN_YBIMG_HOST + img
//			//}
//			// 封面图-默认取二级分类的图片,二级分类图片没有(如晨周报)则取一级
//			coverImg := listImgMap[reportInfo.ClassifyIdSecond]
//			if coverImg == "" {
//				coverImg = listImgMap[reportInfo.ClassifyIdFirst]
//			}
//			reportItem.ReportImgUrl = coverImg
//
//			if classifyParent.ClassifyName == "晨报" && productAuthOk {
//				// 查询当前晨报的所有音频
//				if vList, ok := videoMap[reportInfo.Id]; ok {
//					for _, vd := range vList {
//						vd.VideoImg = reportItem.ReportImgUrl
//					}
//					reportItem.VideoList = vList
//				}
//				reportItem.AuthOk = productAuthOk
//			} else if classifyParent.ClassifyName == "周报" {
//				if wAuth, ok := weekAuthMap[reportInfo.Id]; ok {
//					reportItem.AuthOk = wAuth
//					if wAuth {
//						// 查询当前晨报的所有音频
//						if vList, ok2 := videoMap[reportInfo.Id]; ok2 {
//							for _, vd := range vList {
//								vd.VideoImg = reportItem.ReportImgUrl
//							}
//							reportItem.VideoList = vList
//						}
//					}
//				}
//			} else if authOk, ok := checkPermissionMap[reportInfo.ClassifyNameSecond]; ok && authOk {
//				if reportInfo.VideoUrl != "" {
//					videoTemp := new(response.VideoListItem)
//					videoTemp.VideoUrl = reportInfo.VideoUrl
//					videoTemp.VideoName = reportInfo.VideoName
//					if reportInfo.VideoName == "" {
//						videoTemp.VideoName = reportInfo.Title
//					}
//					videoTemp.VideoPlaySeconds = reportInfo.VideoPlaySeconds
//					videoTemp.VideoImg = reportItem.ReportImgUrl
//					reportItem.VideoList = append(reportItem.VideoList, videoTemp)
//				}
//				reportItem.AuthOk = authOk
//			}
//
//			reportList = append(reportList, reportItem)
//		}
//
//	}
//	ret = new(response.ReportList)
//	ret.List = reportList
//	ret.Paging = response.GetPaging(pageIndex, pageSize, int(total))
//	return
//}
