package controllers

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

// 研选
type ResearchController struct {
	BaseAuthController
}

// @Title 近期更新主题列表
// @Description 近期更新主题列表接口
// @Param   ChartPermissionId   query   int  true       "分类ID"
// @Success 200 {object} models.IndustrialManagementNewList
// @router /theme/newList [get]
func (this *ResearchController) NewList() {
	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")
	//if chartPermissionId < 1 {
	//	br.Msg = "请输入分类ID"
	//	return
	//}
	list, err := models.GetIndustrialManagementNewList("")
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}
	mapHot := make(map[string]int)

	condition := ` ORDER BY sum_num DESC  `
	listHot, err := models.GetThemeHeatList(user.UserId, condition, 0, 3)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}
	for _, v := range listHot {
		mapHot[v.IndustryName] = v.IndustrialManagementId
	}
	for k, v := range list {
		if mapHot[v.IndustryName] > 0 {
			list[k].IsHot = true
		}
	}
	resp := new(models.IndustrialManagementNewList)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 用户收藏列表
// @Description 用户收藏列表接口
// @Param   ChartPermissionId   query   int  true       "分类ID"
// @Success 200 {object} models.ArticleCollectionLIstResp
// @router /collectionList [get]
func (this *ResearchController) CollectionList() {
	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")
	//if chartPermissionId < 1 {
	//	br.Msg = "请输入分类ID"
	//	return
	//}
	var condition string
	condition = `   AND a.article_type_id > 0  AND publish_status = 1 GROUP BY a.article_id ORDER BY collect_num_order DESC, publish_date DESC LIMIT 15 `
	list, err := models.GetArticleCollectionList(condition, user.UserId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}
	for k, v := range list {
		if v.MyCollectNum > 0 {
			list[k].IsCollect = true
		}
	}
	resp := new(models.ArticleCollectionLIstResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 主题热度/近期更新更多,列表
// @Description 主题热度/近期更新更多,列表接口
// @Param   ChartPermissionId   query   int  true       "分类ID"
// @Param   ThemeType   query   int  true       "主题类型,1主题热度、2近期更新 默认1"
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
// @Success 200 {object} models.IndustrialManagementHotListResp
// @router /hotList [get]
func (this *ResearchController) HotList() {
	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")
	//if chartPermissionId < 1 {
	//	br.Msg = "请输入分类ID"
	//	return
	//}
	themeType, _ := this.GetInt("ThemeType")
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize15
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)
	var condition string
	if themeType != 2 {
		condition = `ORDER BY sum_num DESC `
	} else {
		condition = `ORDER BY publish_date DESC `
	}

	total, err := models.GetThemeHeatListCount("")
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}
	list, err := models.GetThemeHeatList(user.UserId, condition, startSize, pageSize)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}
	//newMap := make(map[int]string)
	//listNew, err := models.GetIndustrialManagementNewList("")
	//if err != nil {
	//	br.Msg = "获取信息失败"
	//	br.ErrMsg = "获取产业最新信息失败,Err:" + err.Error()
	//	return
	//}
	//for _, v := range listNew {
	//	newMap[v.IndustrialManagementId] = v.IndustryName
	//}
	condition = ` AND a.article_type_id > 0  `
	listSubjcet, err := models.GetThemeHeatSubjectList(condition)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取标的信息失败,Err:" + err.Error()
		return
	}
	mapHot := make(map[string]int)

	condition = ` ORDER BY sum_num DESC `
	listHot, err := models.GetThemeHeatList(user.UserId, condition, 0, 3)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}
	for _, v := range listHot {
		mapHot[v.IndustryName] = v.IndustrialManagementId
	}
	nowTime := time.Now().Local()
	threeMonBefore := nowTime.AddDate(0, -3, 0)
	for k, v := range list {
		//if newMap[v.IndustrialManagementId] != "" {
		//	list[k].IsNew = true
		//}
		// 关联报告发布时间均在3个月内则标记New
		if v.MinReportTime != "" {
			t, e := time.Parse(utils.FormatDateTime, v.MinReportTime)
			if e != nil {
				err = errors.New("报告最早发布时间有误,GetindustryVideo " + e.Error())
				return
			}
			if t.After(threeMonBefore) {
				list[k].IsNew = true
			}
		}
		if v.FllowNum > 0 {
			list[k].IsFollw = true
		}
		for _, v2 := range listSubjcet {
			if v2.IndustrialManagementId == v.IndustrialManagementId {
				list[k].IndustrialSubjectList = append(list[k].IndustrialSubjectList, v2)
			}
		}
		if mapHot[v.IndustryName] > 0 {
			list[k].IsHot = true
		}
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(models.IndustrialManagementHotListResp)
	resp.Paging = page
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title KOL榜列表
// @Description KOL榜列表接口
// @Param   ChartPermissionId   query   int  true       "分类ID"
// @Success 200 {object} models.DepartmentListResp
// @router /kolList [get]
func (this *ResearchController) KolList() {
	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")
	//if chartPermissionId < 1 {
	//	br.Msg = "请输入分类ID"
	//	return
	//}

	list, err := models.GetDepartmentList(user.UserId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}
	listIndustrial, err := models.GetIndustrialDepartmentList()
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}
	departmentMap := make(map[string]string)
	for k, v := range list {
		if v.FllowNum > 0 {
			list[k].IsFollw = true
		}
		for _, v2 := range listIndustrial {
			if v2.DepartmentId == v.DepartmentId {
				if departmentMap["D"+strconv.Itoa(v2.DepartmentId)+"In"+strconv.Itoa(v2.IndustrialManagementId)] == "" && len(list[k].List) < 4 {
					list[k].List = append(list[k].List, v2)
					departmentMap["D"+strconv.Itoa(v2.DepartmentId)+"In"+strconv.Itoa(v2.IndustrialManagementId)] = v.NickName
				}
			}
		}
	}
	resp := new(models.DepartmentListResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 主题详情
// @Description 主题详情接口
// @Param   IndustrialManagementId   query   int  true       "分类ID"
// @Param   Source   query   int  true       "来源 1:研选,2:报告 默认1"
// @Success 200 {object} models.GetThemeDetailResp
// @router /theme/detail [get]
func (this *ResearchController) ThemeDetail() {
	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
	}
	industrialManagementId, _ := this.GetInt("IndustrialManagementId")
	if industrialManagementId < 1 {
		br.Msg = "请输入产业ID"
		return
	}
	source, _ := this.GetInt("Source")
	if source != 2 {
		source = 1
	}

	var condition string
	if source == 1 {
		condition = `  AND a.category_name LIKE '%研选%' `
	} else {
		condition = `  AND a.category_name  NOT LIKE '%研选%' `
	}
	resp := new(models.GetThemeDetailResp)
	list, err := models.GetThemeDetail(user.UserId, industrialManagementId, condition)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}

	var itemsNull []*models.GetThemeAericleListResp
	subjectMap := make(map[string]string)
	articleMap := make(map[int]int)
	for _, v := range list {
		resp.IndustryName = v.IndustryName
		resp.IndustrialManagementId = v.IndustrialManagementId
		itemSubJect := new(models.IndustrialSubject)
		itemSubJect.SubjectName = v.SubjectName
		itemSubJect.IndustrialSubjectId = v.IndustrialSubjectId
		if subjectMap[v.SubjectName] == "" && v.SubjectName != "" {
			resp.ListSubject = append(resp.ListSubject, itemSubJect)
		}

		subjectMap[v.SubjectName] = v.IndustryName
		if v.FllowNum > 0 {
			resp.IsFollw = true
		}

		if v.SubjectName == "" {
			item := new(models.GetThemeAericleListResp)
			item.ArticleId = v.ArticleId
			item.Title = v.Title
			item.PublishDate = v.PublishDate
			item.SubjectName = v.SubjectName
			item.DepartmentId = v.DepartmentId
			item.NickName = v.NickName
			item.Pv = v.Pv
			item.CollectNum = v.CollectNum
			itemsNull = append(itemsNull, item)

		}
	}

	for _, v := range resp.ListSubject {
		subjetcGroup := new(models.GetThemeAericleListBuSubjectResp)
		for _, v2 := range list {
			if v2.IndustrialSubjectId == v.IndustrialSubjectId && articleMap[v2.ArticleId] == 0 {
				item := new(models.GetThemeAericleListResp)
				item.ArticleId = v2.ArticleId
				item.Title = v2.Title
				item.PublishDate = v2.PublishDate
				item.SubjectName = v2.SubjectName
				item.IndustrialSubjectId = v2.IndustrialSubjectId
				for _, v3 := range list {
					if v3.ArticleId == v2.ArticleId && v3.SubjectName != v2.SubjectName && v3.SubjectName != "" {
						item.SubjectName += "/" + v3.SubjectName
					}
				}
				item.DepartmentId = v2.DepartmentId
				item.NickName = v2.NickName
				item.Pv = v2.Pv
				item.CollectNum = v2.CollectNum
				item.MyCollectNum = v2.MyCollectNum
				if v2.MyCollectNum > 0 {
					item.IsCollect = true
				}
				resp.List = append(resp.List, item)
				articleMap[v2.ArticleId] = v2.ArticleId
				//subjetcGroup.List = append(subjetcGroup.List, item)
			}
			subjetcGroup.SubjectName = v.SubjectName
		}

	}
	//当标的为空时进行合并
	if len(itemsNull) > 0 {
		for _, v := range itemsNull {
			resp.List = append(resp.List, v)
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 研选作者详情
// @Description 研选作者详情接口
// @Param   DepartmentId   query   int  true       "作者ID"
// @Success 200 {object} models.DepartmentDetailResp
// @router /departmentId/detail [get]
func (this *ResearchController) DepartmentIdDetail() {
	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
	}
	departmentId, _ := this.GetInt("DepartmentId")
	if departmentId < 1 {
		br.Msg = "请输入作者ID"
		return
	}
	resp := new(models.DepartmentDetailResp)
	detail, err := models.GetDepartmentDetail(user.UserId, departmentId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取作者信息失败,Err:" + err.Error()
		return
	}
	resp.DepartmentId = detail.DepartmentId
	resp.NickName = detail.NickName
	resp.ImgUrl = detail.ImgUrl
	resp.FllowNum = detail.FllowNum
	resp.ArticleNum = detail.ArticleNum
	resp.CollectNum = detail.CollectNum
	if detail.MyFllowNum > 0 {
		resp.IsFllow = true
	}
	var condition string
	condition = `  AND a.department_id = ` + strconv.Itoa(departmentId) + ` ORDER BY a.publish_date DESC  `
	list, err := models.GetArticleCollectionList(condition, user.UserId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取文章列表失败,Err:" + err.Error()
		return
	}
	for k, v := range list {
		if v.MyCollectNum > 0 {
			list[k].IsCollect = true
		}
	}

	condition = ` AND a.department_id =  ` + strconv.Itoa(departmentId)
	listIndustrial, err := models.GetIndustrialManagementNewList(condition)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}
	resp.List = list
	resp.ListIndustrial = listIndustrial
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 文章相关热门收藏
// @Description 文章相关热门收藏接口
// @Param   ArticleId   query   int  true       "文章ID"
// @Success 200 {object} models.ArticleCollectionLIstResp
// @router /article/hotList [get]
func (this *ResearchController) ArticleHotList() {
	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
	}
	articleId, _ := this.GetInt("ArticleId")
	if articleId < 1 {
		br.Msg = "请输入分类ID"
		return
	}
	var condition string
	condition = ` AND a.article_id IN (SELECT article_id FROM cygx_industrial_article_group_management WHERE industrial_management_id IN (SELECT industrial_management_id  FROM cygx_industrial_article_group_management  WHERE  article_id = ` + strconv.Itoa(articleId) + ` ) ) AND a.article_id != ` + strconv.Itoa(articleId) + ` AND a.category_name LIKE '%研选%' AND publish_status = 1 GROUP BY a.article_id ORDER BY collect_num DESC, publish_date DESC LIMIT 3 `
	list, err := models.GetArticleCollectionList(condition, user.UserId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}
	for k, v := range list {
		if v.MyCollectNum > 0 {
			list[k].IsCollect = true
		}
	}
	resp := new(models.ArticleCollectionLIstResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 热搜关键词
// @Description 热搜关键词接口
// @Success 200 {object} models.UserSearchKeyWordListResp
// @router /hotKeyWord [get]
func (this *ResearchController) HotKeyWord() {
	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
	}
	//本来应该放在config控制器下,与未上线的代码冲突,所以放在这里
	list, err := models.GetUserSearchKeyWord()
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}
	resp := new(models.UserSearchKeyWordListResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 研选文章类型列表
// @Description 研选文章类型列表接口
// @Success 200 {object} models.CygxArticleTypeListResp
// @router /article/typeList [get]
func (this *ResearchController) ArticleType() {
	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
	}
	var condition string
	condition = " AND is_show_yanx  = 1 "
	list, err := models.GetCygxArticleTypeListCondition(condition)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}
	resp := new(models.CygxArticleTypeListResp)
	for _, v := range list {
		item := models.CygxArticleTypeResp{
			ArticleTypeId:   v.ArticleTypeId,
			ArticleTypeName: v.ArticleTypeName,
			ButtonStyle:     v.ButtonStyle,
		}
		resp.List = append(resp.List, &item)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 研选最新报告列表
// @Description 研选最新报告列表接口
// @Success 200 {object} models.IndustrialManagementNewList
// @router /article/newList [get]
func (this *ResearchController) ArticleNewList() {
	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
	}
	var condition string
	condition = `   AND a.article_type_id > 0  AND publish_status = 1 GROUP BY a.article_id ORDER BY collect_num_order DESC, publish_date DESC LIMIT 15 `
	list, err := models.GetArticleCollectionList(condition, user.UserId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}
	for k, v := range list {
		if v.MyCollectNum > 0 {
			list[k].IsCollect = true
		}
	}
	resp := new(models.ArticleCollectionLIstResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}