package controllers

import (
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/services"
	"hongze/hongze_cygx/utils"
	"time"
)

// 报告榜单
type ReportBillboardController struct {
	BaseAuthController
}

// @Title 报告榜单table栏
// @Description 报告榜单table栏
// @Success 200 {object} models.ReportBillboardTableListResp
// @router /table/list [get]
func (this *ReportBillboardController) CompanyTableList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	user := this.User
	if user == nil {
		br.Msg = "请重新登录"
		br.Ret = 408
		return
	}
	ListPermission := []*models.ChartPermission{{PermissionName: utils.YI_YAO_NAME, ChartPermissionId: utils.YI_YAO_ID}, {PermissionName: utils.XIAO_FEI_NAME, ChartPermissionId: utils.XIAO_FEI_ID}, {PermissionName: utils.KE_JI_NAME, ChartPermissionId: utils.KE_JI_ID}, {PermissionName: utils.ZHI_ZAO_NAME, ChartPermissionId: utils.ZHI_ZAO_ID}}
	ListAllPermission := []*models.ChartPermission{{PermissionName: utils.YI_YAO_NAME, ChartPermissionId: utils.YI_YAO_ID}, {PermissionName: utils.XIAO_FEI_NAME, ChartPermissionId: utils.XIAO_FEI_ID}, {PermissionName: utils.KE_JI_NAME, ChartPermissionId: utils.KE_JI_ID}, {PermissionName: utils.ZHI_ZAO_NAME, ChartPermissionId: utils.ZHI_ZAO_ID}, {PermissionName: utils.CE_LUE_NAME, ChartPermissionId: utils.CE_LUE_ID}}
	List := []*models.ReportBillboardTableResp{{Name: "产业关注榜", Source: 1, List: ListPermission}, {Name: "阅读飙升榜", Source: 2, List: ListAllPermission}, {Name: "报告收藏榜", Source: 3, List: ListAllPermission}}
	resp := new(models.ReportBillboardTableListResp)
	resp.List = List
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 产业关注榜
// @Description 获取产业关注榜接口
// @Param   ChartPermissionId   query   int  false       "行业ID"
// @Success 200 {object} models.IndustrialManagementList
// @router /industry/fllowList [get]
func (this *ReportBillboardController) FllowList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	user := this.User
	if user == nil {
		br.Msg = "请重新登录"
		br.Ret = 408
		return
	}
	uid := user.UserId
	// 行业ID暂时不需要了调整为非必填
	chartPermissionId, _ := this.GetInt("ChartPermissionId")

	// 查询有已归类行业报告的行业IDs
	activeIndustryIds, e := models.GetActiveArticleIndustryIds()
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取已归类行业失败, Err:" + e.Error()
		return
	}
	activeIndustryLen := len(activeIndustryIds)

	topNum := utils.PageSize15
	var condition, subCond string
	var pars, subPars []interface{}
	if chartPermissionId > 0 {
		condition += ` 	AND man.chart_permission_id = ?  `
		pars = append(pars, chartPermissionId)
	}
	if activeIndustryLen > 0 {
		condition += ` AND man.industrial_management_id IN (` + utils.GetOrmInReplace(activeIndustryLen) + `)`
		pars = append(pars, activeIndustryIds)
	}
	//nowTime := time.Now().Local()
	//startTime := nowTime.AddDate(0, -1, 0)
	//endTime := nowTime.AddDate(0, 0, -1)
	//condition += ` AND idf.create_time BETWEEN ? AND ?`
	//pars = append(pars, startTime, endTime)

	// 查询近一个月至昨日关注度最高的15个产业(不再指定行业, chartPermissionId可筛选行业)
	list, e := models.GetTopIndustryFollowData(0, topNum, condition, pars)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取关注度最高的产业数据失败, Err:" + e.Error()
		return
	}
	industryIdArr := make([]int, 0)
	for i := range list {
		industryIdArr = append(industryIdArr, list[i].IndustrialManagementId)
	}
	idsLen := len(industryIdArr)

	// 查询当前用户关注的产业
	followList, err := models.GetUserFllowIndustrialList(uid)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，GetUserFllowIndustrialList Err:" + err.Error()
		return
	}
	followMap := make(map[int]int, 0)
	for i := range followList {
		followMap[followList[i].IndustrialManagementId] = 1
	}

	// 查询产业标的
	if idsLen > 0 {
		subCond = `AND s.industrial_management_id IN (  ` + utils.GetOrmInReplace(idsLen) + ` )  `
		subPars = append(subPars, industryIdArr)
	}
	subjectList, err := models.GetSubjectList(subPars, subCond)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，GetSubjectList Err:" + err.Error()
		return
	}
	subjectMap := make(map[int][]*models.IndustrialSubject)
	for i := range subjectList {
		item := new(models.IndustrialSubject)
		item.SubjectName = subjectList[i].SubjectName
		item.IndustrialManagementId = subjectList[i].IndustrialManagementId
		subjectMap[subjectList[i].IndustrialManagementId] = append(subjectMap[subjectList[i].IndustrialManagementId], item)
	}

	// 查询行业
	permissionList, e := models.GetChartPermissionAll("")
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取行业信息失败, Err: " + e.Error()
		return
	}
	permissionMap := make(map[int]string, 0)
	for i := range permissionList {
		permissionMap[permissionList[i].ChartPermissionId] = permissionList[i].PermissionName
	}

	for k, v := range list {
		list[k].IsFollow = followMap[v.IndustrialManagementId]
		list[k].IndustrialSubjectList = subjectMap[v.IndustrialManagementId]
		list[k].PermissionName = permissionMap[v.ChartPermissionId]
	}

	//查询产业视频
	industrialVideoMap := make(map[int]*models.MicroVideoSimpleInfo)
	var industrialManagementIds []int
	for _, v := range list {
		if v.IndustrialManagementId > 0 {
			industrialManagementIds = append(industrialManagementIds, v.IndustrialManagementId)
		}
	}

	// 用户权限
	authInfo, permissionArr, e := services.GetUserRaiPermissionInfo(user.UserId, user.CompanyId)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取用户权限失败, Err: " + e.Error()
		return
	}
	mapUPdateTime := make(map[int]string)

	if len(industrialManagementIds) > 0 {
		// 获取默认图配置
		_, videoMap, _, _, e := services.GetMicroRoadShowDefaultImgConfig()
		if e != nil {
			br.Msg = "获取视频默认配置图失败"
			br.ErrMsg = "获取视频默认配置图失败, Err: " + e.Error()
			return
		}
		videoList, err := models.GetMicroRoadshowVideoByIndustryIds(industrialManagementIds)
		if err != nil {
			br.Msg = "产业视频列表失败"
			br.ErrMsg = "产业视频列表失败, Err: " + err.Error()
			return
		}
		for _, v := range videoList {
			tmp := &models.MicroVideoSimpleInfo{
				Id:                  v.VideoId,
				Title:               "5min逻辑【" + v.IndustryName + "】解析",
				ResourceUrl:         v.VideoUrl,
				BackgroundImg:       v.ImgUrl,
				PlaySeconds:         v.VideoDuration,
				DetailImgUrl:        v.DetailImgUrl,
				ChartPermissionId:   v.ChartPermissionId,
				ChartPermissionName: v.ChartPermissionName,
			}
			if tmp.BackgroundImg == "" {
				tmp.BackgroundImg = videoMap[v.ChartPermissionId]
			}
			industrialVideoMap[v.IndustryId] = tmp
		}
		//获取这些产业下最新更新的文章
		listUpdateTime, err := models.GetNewArticleDetailByIndustrialIds(industrialManagementIds)
		if err != nil && err.Error() != utils.ErrNoRow() {
			return
		}
		for _, v := range listUpdateTime {
			mapUPdateTime[v.IndustrialManagementId] = v.PublishDate
		}

		//时间线的更新时间
		//	maptimelineUPdateTime := make(map[int]string)
		listtimelinePublishdate, err := models.GetTimeLineReportIndustrialPublishdateList(industrialManagementIds)
		if err != nil && err.Error() != utils.ErrNoRow() {
			return
		}
		for _, v := range listtimelinePublishdate {
			if mapUPdateTime[v.IndustrialManagementId] != "" {
				if utils.StrTimeToTime(v.PublishDate).After(utils.StrTimeToTime(mapUPdateTime[v.IndustrialManagementId])) {
					mapUPdateTime[v.IndustrialManagementId] = v.PublishDate
				}
			}
		}
	}

	for k, v := range list {
		//展示产业视频
		if video, ok := industrialVideoMap[v.IndustrialManagementId]; ok {
			//控制用户权限
			// 权限
			au := new(models.UserPermissionAuthInfo)
			au.SellerName = authInfo.SellerName
			au.SellerMobile = authInfo.SellerMobile
			au.HasPermission = authInfo.HasPermission
			au.OperationMode = authInfo.OperationMode
			if au.HasPermission == 1 {
				// 非宏观权限进一步判断是否有权限
				if video.ChartPermissionId != utils.HONG_GUAN_ID && !utils.InArrayByStr(permissionArr, video.ChartPermissionName) {
					au.HasPermission = 2
				}
			}
			// 无权限的弹框提示
			if au.HasPermission != 1 {
				if au.OperationMode == services.UserPermissionOperationModeCall {
					au.PopupMsg = services.UserPermissionPopupMsgCallMicroVideo
				} else {
					au.PopupMsg = services.UserPermissionPopupMsgApplyMicroVideo
				}
				video.ResourceUrl = ""
			}
			list[k].AuthInfo = au
			list[k].IndustryVideo = video
		}
	}

	page := paging.GetPaging(1, topNum, len(list))
	resp := new(models.IndustrialManagementList)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 阅读飙升榜/报告收藏榜
// @Description 获取阅读飙升榜/报告收藏榜接口
// @Param   ChartPermissionId   query   int  false       "分类ID"
// @Param   Source   query   int  true       "来源 2：阅读飙升 ，3：报告收藏"
// @Success 200 {object} models.ArticleReportBillboardLIstResp
// @router /industry/readList [get]
func (this *ReportBillboardController) ReadList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	user := this.User
	if user == nil {
		br.Msg = "请重新登录"
		br.Ret = 408
		return
	}
	chartPermissionId, _ := this.GetInt("ChartPermissionId")
	source, _ := this.GetInt("Source")
	sourceArr := []int{2, 3}
	if !utils.InArrayByInt(sourceArr, source) {
		br.Msg = "来源有误"
		return
	}

	topNum := utils.PageSize15
	list := make([]*models.ArticleReportBillboardResp, 0)

	// 阅读飙升榜
	if source == 2 {
		var topCond string
		var topPars []interface{}
		if chartPermissionId > 0 {
			topCond += ` AND chart_permission_id = ?`
			topPars = append(topPars, chartPermissionId)
		}
		topList, e := models.GetTopReadRecordArticleListByCondition(topNum, topCond, topPars)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取报告阅读增量排行榜失败, Err:" + e.Error()
			return
		}
		for i := range topList {
			list = append(list, &models.ArticleReportBillboardResp{
				ArticleId:      topList[i].ArticleId,
				Title:          topList[i].Title,
				PublishDate:    topList[i].PublishDate,
				PermissionName: topList[i].PermissionName,
			})
		}
	}

	// 报告收藏榜
	if source == 3 {
		var collectCond string
		var collectPars []interface{}
		if chartPermissionId > 0 {
			collectCond += ` AND m.chart_permission_id = ?`
			collectPars = append(collectPars, chartPermissionId)
		}
		// 根据关注时间一个月前至昨日的增量数据排序
		nowTime := time.Now().Local()
		startTime := nowTime.AddDate(0, -1, 0)
		endTime := nowTime.AddDate(0, 0, -1)
		collectCond += ` AND ac.create_time BETWEEN ? AND ?`
		collectPars = append(collectPars, startTime, endTime)
		collectList, e := models.GetReportCollectionBillboardList(topNum, collectPars, collectCond)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取报告收藏排行榜失败, Err:" + e.Error()
			return
		}
		list = collectList
	}
	articleIds := make([]int, 0)
	for i := range list {
		articleIds = append(articleIds, list[i].ArticleId)
	}

	articleMapPv := services.GetArticleHistoryByArticleId(articleIds)                       //文章Pv
	articleCollectMap, _ := services.GetCygxArticleCollectMap(user.UserId)                  //用户收藏的文章
	articleCollectNumMap, _ := services.GetCygxArticleCollectNumMapByArtcileIds(articleIds) //文章收藏的数量

	// 报告关联产业信息
	industryMap := make(map[int][]*models.IndustrialManagementIdInt, 0)
	if len(articleIds) > 0 {
		var industryCond string
		var industryPars []interface{}
		industryCond += ` AND mg.article_id IN (` + utils.GetOrmInReplace(len(articleIds)) + `)`
		industryPars = append(industryPars, articleIds)
		industryList, e := models.GetIndustrialListByarticleId(industryPars, industryCond)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取报告关联的产业信息失败, Err: " + e.Error()
			return
		}
		for i := range industryList {
			v := industryList[i]
			industryMap[v.ArticleId] = append(industryMap[v.ArticleId], &models.IndustrialManagementIdInt{
				ArticleId:              v.ArticleId,
				IndustrialManagementId: v.IndustrialManagementId,
				IndustryName:           v.IndustryName,
			})
		}
	}
	for k, v := range list {
		if len(industryMap[v.ArticleId]) > 0 {
			list[k].List = industryMap[v.ArticleId]
		} else {
			list[k].List = make([]*models.IndustrialManagementIdInt, 0)
		}
		v.Pv = articleMapPv[v.ArticleId]
		v.IsCollect = articleCollectMap[v.ArticleId]
		v.CollectNum = articleCollectNumMap[v.ArticleId]
	}

	resp := new(models.ArticleReportBillboardLIstResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}
