package cygx

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"github.com/tealeg/xlsx"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/services"
	cygxService "hongze/hz_crm_api/services/cygx"
	"hongze/hz_crm_api/utils"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// 报告精选
type ReportSelectionController struct {
	controllers.BaseAuthController
}

// @Title 报告精选内容的保存与发布
// @Description 报告精选内容的保存与发布接口
// @Param	request	body cygx.AddCygxReportSelection true "type json string"
// @Success 200 操作成功
// @router /reportSelection/PreserveAndPublish [post]
func (this *ReportSelectionController) PreserveAndPublish() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	var req cygx.AddCygxReportSelection
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.AddType != "1" && req.AddType != "2" {
		br.Msg = "请选择正确的添加方式！"
		return
	}
	if req.AddType == "2" && req.InheritPeriods == "" {
		br.Msg = "请选择继承第几期！"
		return
	}
	list := req.List
	listChartSummary := req.ListChartSummary
	reportLink := req.ReportLink
	if len(list) < 1 {
		br.Msg = "产业资源内容不可为空！"
		return
	}
	if len(listChartSummary) < 1 {
		br.Msg = "行业核心逻辑汇总不能为空！"
		return
	}
	if reportLink == "" {
		br.Msg = "详细报告链接，不能为空！"
		return
	}
	articleIdLink, err := cygxService.GetReportLinkToArticleid(reportLink)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "解析报告链接ID失败，Err:" + err.Error()
		return
	}
	if articleIdLink == 0 {
		br.Msg = "详细报告链接格式错误"
		br.ErrMsg = "解析报告链接ID失败，报告链接:" + reportLink
		return
	}
	var items []*cygx.CygxReportSelectionLog
	var itemsChart []*cygx.CygxReportSelectionChartLog

	condition := ` AND have_publish = 1 `
	var pars []interface{}
	total, err := cygx.GetCygxReportSelection(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	itemCrs := new(cygx.CygxReportSelection)
	itemCrs.AdminId = AdminUser.AdminId
	itemCrs.AdminName = AdminUser.RealName
	itemCrs.Title = req.Title
	itemCrs.Department = req.Department
	itemCrs.AddType = req.AddType
	itemCrs.PublishStatus = req.DoType
	if req.DoType == 1 {
		itemCrs.HavePublish = 1
		itemCrs.Periods = strconv.Itoa(total + 1)
	}
	itemCrs.PublishDate = utils.StrTimeToTime(req.PublishDate + " 00:00:00")

	itemCrs.CreateTime = time.Now()
	itemCrs.LastUpdatedTime = time.Now()
	itemCrs.InheritPeriods = req.InheritPeriods
	itemCrs.ProductDescription = req.ProductDescription
	itemCrs.UpdateDescription = req.UpdateDescription
	itemCrs.ReportLink = req.ReportLink
	itemCrs.FocusOn = cygxService.GetRichtext(req.FocusOn)
	itemCrs.MarketStrategy = cygxService.GetRichtext(req.MarketStrategy)
	for _, v := range list {
		item := new(cygx.CygxReportSelectionLog)
		item.ChartPermissionId = v.ChartPermissionId
		item.CreateTime = time.Now()
		item.Body = cygxService.GetRichtext(v.Body)
		item.IndustrialSubjectId = v.IndustrialSubjectId
		item.SubjectName = v.IndustrialSubjectName
		item.IndustrialManagementId = v.IndustrialManagementId
		item.OverviewArticleId = v.OverviewArticleId
		item.IsNew = v.IsNew
		item.IsShowOverviewArticle = v.IsShowOverviewArticle
		if len(v.CompanyLabel) > 0 {
			item.CompanyLabel = cygxService.ArticleComPanyLabelToStr(v.CompanyLabel)
		}
		items = append(items, item)
	}
	for _, v := range listChartSummary {
		item := new(cygx.CygxReportSelectionChartLog)
		item.ChartPermissionId = v.ChartPermissionId
		item.CreateTime = time.Now()
		item.Body = cygxService.GetRichtext(v.BodyChartSummary)
		itemsChart = append(itemsChart, item)
	}
	if req.ArticleId == 0 {
		articleId, err := cygx.AddCygxReportSelectionOrm(itemCrs, items, itemsChart)
		if err != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "发布失败,Err:" + err.Error()
			return
		}
		req.ArticleId = int(articleId)
	} else {
		detail, err := cygx.GetCygxReportSelectionInfoById(req.ArticleId)
		if err != nil {
			br.Msg = "内容不存在"
			br.ErrMsg = "操作失败,Err:" + err.Error()
			return
		}
		if itemCrs.PublishStatus == 0 {
			itemCrs.PublishStatus = detail.PublishStatus
			itemCrs.AdminId = detail.AdminId
			itemCrs.AdminName = detail.AdminName
		}
		if detail.HavePublish == 1 {
			itemCrs.Periods = detail.Periods
			itemCrs.HavePublish = detail.HavePublish
		}
		itemCrs.ArticleId = req.ArticleId
		_, err = cygx.UpdateCygxReportSelectionOrm(itemCrs, items, itemsChart)
		if err != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "发布失败,Err:" + err.Error()
			return
		}
	}
	//if req.DoType == 1 {
	//cygxService.DoThisWeekLastWeekWxTemplateMsg(itemCrs.Title, itemCrs.PublishDate.Format(utils.FormatDateTime), itemCrs.ProductDescription, req.ArticleId, 1)
	//}
	//生成音频文件
	//articleId := req.ArticleId
	//existMap := make(map[int]int)
	//var content string
	//content = "产品说明" + req.ProductDescription + "变更说明" + req.UpdateDescription + "近期重点关注方向" + req.FocusOn
	//listLog, err := cygx.GetReportSelectionlogListAll(articleId)
	//if err != nil {
	//	br.Msg = "获取失败"
	//	br.ErrMsg = "获取失败，Err:" + err.Error()
	//	return
	//}
	//for _, v := range listLog {
	//	if existMap[v.ChartPermissionId] == 0 {
	//		content += v.PermissionName + "领域深度调研和报告"
	//		listSonLog, err := cygx.GetReportSelectionlogSonListAll(articleId, v.ChartPermissionId)
	//		if err != nil && err.Error() != utils.ErrNoRow() {
	//			br.Msg = "获取信息失败"
	//			br.ErrMsg = "获取信息失败,Err:" + err.Error()
	//			return
	//		}
	//		if len(listSonLog) > 0 {
	//			for _, v2 := range listSonLog {
	//				content += v2.SubjectName + v2.Body
	//			}
	//		}
	//	}
	//	existMap[v.ChartPermissionId] = v.ChartPermissionId 0
	//}
	go cygxService.UpdateReportSelectionResourceData(req.ArticleId) //首页最新页面数据逻辑处理 V11.1.1
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.IsAddLog = true
}

// @Title 删除报告精选内容
// @Description 删除报告精选内容接口
// @Param   request	body cygx.ResearchSummaryId true "type json string"
// @Success Ret=200
// @router /reportSelection/delete [post]
func (this *ReportSelectionController) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req cygx.ResearchSummaryId
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	articleId := req.ArticleId
	detail, err := cygx.GetCygxReportSelectionInfoById(articleId)
	if err != nil {
		br.Msg = "内容不存在"
		br.ErrMsg = "操作失败,Err:" + err.Error()
		return
	}
	if detail.HavePublish != 0 {
		br.Msg = "删除失败"
		br.ErrMsg = "已经存在期数无法删除"
		return
	}
	err = cygx.DeleteCygxReportSelection(articleId)
	if err != nil {
		br.Msg = "删除信息失败"
		br.ErrMsg = "删除信息失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "已删除"
	br.IsAddLog = true
}

// @Title  报告精选内容详情
// @Description  报告精选内容详情接口
// @Param   ArticleId   query   int  true       "报告Id"
// @Param   Periods   query   string  true       "期数Id"
// @Success Ret=200 {object} cygx.DetailCygxReportSelectionRep
// @router /reportSelection/detail [get]
func (this *ReportSelectionController) Detail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	var errArt error
	detail := new(cygx.CygxReportSelectionRep)
	articleId, _ := this.GetInt("ArticleId")
	periods := this.GetString("Periods")

	if articleId > 0 && periods == "" {
		detail, errArt = cygx.GetCygxReportSelectionInfoById(articleId)
		if errArt != nil {
			br.Msg = "内容不存在"
			br.ErrMsg = "内容不存在,Err:" + errArt.Error()
			return
		}
	} else {
		detail, errArt = cygx.GetCygxReportSelectionInfoByPeriods(periods)
		if errArt != nil {
			br.Msg = "内容不存在"
			br.ErrMsg = "内容不存在通过期数获取详情错误,Err:" + errArt.Error() + "期数：" + periods
			return
		}
	}
	articleId = detail.ArticleId
	resp := new(cygx.DetailCygxReportSelectionRep)
	resp.ArticleId = detail.ArticleId
	resp.AddType = detail.AddType
	resp.InheritPeriods = detail.InheritPeriods
	resp.Title = detail.Title
	resp.Department = detail.Department
	resp.PublishStatus = detail.PublishStatus
	resp.PublishDate = utils.StrTimeToTime(detail.PublishDate).Format("2006-01-02")
	resp.ProductDescription = detail.ProductDescription
	resp.UpdateDescription = detail.UpdateDescription
	resp.FocusOn = detail.FocusOn
	resp.MarketStrategy = detail.MarketStrategy
	resp.ReportLink = detail.ReportLink
	if detail.InheritPeriods != "" {
		resp.InheritPeriodsName = "第" + detail.InheritPeriods + "期"
	}
	var condition string
	condition = ` AND chart_permission_id IN (19,20,21,22) `
	listMore, err := cygx.GetChartPermissionDetail(condition)
	var list []*cygx.CygxReportSelectionChart
	//排序方式修改
	permissionNameList := []cygx.CygxChartPermissionName{}
	//获取行业核心逻辑汇总
	listChartLog, err := cygx.GetCygxReportSelectionChartLogRepList(articleId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	permissionNameMap, err := services.GetPermissionNameMap()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败 GetPermissionNameMap，Err:" + err.Error()
		return
	}
	mapChartLog := make(map[string]string)
	for _, v := range listChartLog {
		v.ChartPermissionName = permissionNameMap[v.ChartPermissionId]
		mapChartLog[v.ChartPermissionName] = v.BodyChartSummary
		permissionNameList = append(permissionNameList, cygx.CygxChartPermissionName{v.ChartPermissionName})
	}
	for _, v := range permissionNameList {
		for _, v2 := range listMore {
			v2.ChartPermissionName = permissionNameMap[v2.ChartPermissionId]
			if v.ChartPermissionName == v2.ChartPermissionName {
				item := new(cygx.CygxReportSelectionChart)
				item.ChartPermissionName = v2.ChartPermissionName
				item.ChartPermissionId = v2.ChartPermissionId
				//item.List = make([]string, 0)
				list = append(list, item)
			}
		}
	}

	//获取关联的文章信息
	mapArticle := make(map[int]string)
	listSelectionLog, err := cygx.GetReportSelectionlogListAll(articleId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "GetReportSelectionlogListAll，Err:" + err.Error()
		return
	}
	articleStockMap, _ := cygxService.GetArticleStockMap()
	var overviewArticleIdArr []int
	for _, v := range listSelectionLog {
		if v.OverviewArticleId > 0 {
			overviewArticleIdArr = append(overviewArticleIdArr, v.OverviewArticleId)
		}
	}
	for _, v := range articleStockMap {
		overviewArticleIdArr = append(overviewArticleIdArr, v)
	}
	lenActivityIds := len(overviewArticleIdArr)
	if lenActivityIds > 0 {
		var pars []interface{}
		conditionArticle := `  AND article_id IN (` + utils.GetOrmInReplace(lenActivityIds) + `)  `
		pars = append(pars, overviewArticleIdArr)
		articleList, err := cygx.GetCygxArticleList(conditionArticle, pars, 0, lenActivityIds)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "GetCygxArticleList，Err:" + err.Error()
			return
		}
		for _, v := range articleList {
			mapArticle[v.ArticleId] = v.Title
		}
	}
	//获取标的关联的日志
	for k, v := range list {
		listSon, err := cygx.GetCygxReportSelectionLogRepListSon(articleId, v.ChartPermissionId)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取子分类失败，Err:" + err.Error()
			return
		}
		for kIndustrial, vIndustrial := range listSon {
			//如果报告精选关联的产业被删除了 则做以下处理
			//if vIndustrial.IndustrialManagementName == "" {
			industrialNames, err := cygx.GetindustrialManagementNamesBySubjectName(vIndustrial.IndustrialSubjectName, vIndustrial.ChartPermissionId)
			if err != nil {
				br.Msg = "获取失败！"
				br.ErrMsg = "获取删除删除之后的产业失败，Err:" + err.Error() + vIndustrial.IndustrialSubjectId
				return
			}
			if vIndustrial.Label != "" {
				vIndustrial.CompanyLabel = strings.Split(vIndustrial.Label, "{|}")
			}
			listSon[kIndustrial].IndustrialManagementName = industrialNames
			listSon[kIndustrial].OverviewArticleId = articleStockMap[vIndustrial.IndustrialSubjectName]
			listSon[kIndustrial].OverviewArticleTitle = mapArticle[listSon[kIndustrial].OverviewArticleId]
			if periods != "" {
				listSon[kIndustrial].IsNew = 0
			}
		}
		list[k].List = listSon
		list[k].BodyChartSummary = mapChartLog[v.ChartPermissionName]
	}
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 报告精选列表
// @Description 获取报告精选列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   PublishStatus   query   int  false       "发布状态 ，1未发布，1已发布，传2查询所有"
// @Param   StartDate   query   string  false       "开始时间 ，列如2021-03-06 "
// @Param   EndDate   query   string  false       "结束时间，列如2021-03-06 "
// @Success 200 {object} cygx.CygxReportSelectionListRep
// @router /reportSelection/list [get]
func (this *ReportSelectionController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	publishStatus, _ := this.GetInt("PublishStatus")
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)
	var condition string
	var pars []interface{}
	if startDate != "" {
		condition += ` AND rs.publish_date >= ` + "'" + startDate + " 00:00:00'"
	}
	if endDate != "" {
		condition += ` AND rs.publish_date <= ` + "'" + endDate + " 23:59:59'"
	}
	if publishStatus == 0 || publishStatus == 1 {
		condition += ` AND rs.publish_status = ` + strconv.Itoa(publishStatus)
	}
	total, err := cygx.GetCygxReportSelection(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	list, err := cygx.GetReportSelectionList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	for k, v := range list {
		if v.Periods != "" && v.Periods != "0" {
			list[k].Periods = "第" + v.Periods + "期"
		} else {
			list[k].Periods = ""
		}
		list[k].PublishDate = utils.StrTimeToTime(v.PublishDate).Format("2006-01-02")
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(cygx.CygxReportSelectionListRep)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title   报告精选的发布与取消发布
// @Description   报告精选的发布与取消发布接口
// @Param	request	body cygx.ResearchSummaryId true "type json string"
// @Success 200 操作成功
// @router /reportSelection/PublishAndCancel [post]
func (this *ReportSelectionController) PublishAndCancel() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	var req cygx.ResearchSummaryId
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	articleId := req.ArticleId
	detail, err := cygx.GetCygxReportSelectionInfoById(articleId)
	if err != nil {
		br.Msg = "内容不存在"
		br.ErrMsg = "操作失败,Err:" + err.Error()
		return
	}
	item := new(cygx.CygxReportSelectionRep)
	item.ArticleId = articleId
	if detail.PublishStatus == 0 {
		item.PublishStatus = 1
		item.AdminId = AdminUser.AdminId
		item.AdminName = AdminUser.RealName
		//cygxService.DoThisWeekLastWeekWxTemplateMsg(detail.Title, detail.PublishDate, detail.ProductDescription, req.ArticleId, 1)
	} else {
		item.AdminId = detail.AdminId
		item.AdminName = detail.AdminName
		item.PublishStatus = 0
	}
	if detail.HavePublish == 0 {
		condition := ` AND have_publish = 1 `
		var pars []interface{}
		total, err := cygx.GetCygxReportSelection(condition, pars)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		item.Periods = strconv.Itoa(total + 1)

	} else {
		item.Periods = detail.Periods
	}
	err = cygx.ReportSelectionPublishAndCancel(item)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败,Err:" + err.Error()
		return
	}
	go cygxService.UpdateReportSelectionResourceData(articleId) //首页最新页面数据逻辑处理 V11.1.1
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.IsAddLog = true
}

// @Title  报告精选初始模板
// @Description  报告精选初始模板接口
// @Success Ret=200 {object} cygx.CygxRSlChartPermissionIcoTmpList
// @router /reportSelection/detailTemplate [get]
func (this *ReportSelectionController) DetailTemplate() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	resp := new(cygx.CygxRSlChartPermissionIcoTmpList)
	var condition string
	var list []*cygx.CygxRSlChartPermissionIcoTmp
	condition = ` AND chart_permission_id IN (19,20,21,22) `
	listMore, err := cygx.GetChartPermissionIcoNew(condition)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	//排序方式修改
	permissionNameList := []cygx.CygxChartPermissionName{{ChartPermissionName: "消费"}, {ChartPermissionName: "医药"}, {ChartPermissionName: "科技"}, {ChartPermissionName: "智造"}}
	for _, v := range permissionNameList {
		for _, v2 := range listMore {
			if v.ChartPermissionName == v2.ChartPermissionName {
				item := new(cygx.CygxRSlChartPermissionIcoTmp)
				item.ChartPermissionName = v2.ChartPermissionName
				item.ChartPermissionSort = v2.ChartPermissionSort
				item.ChartPermissionId = v2.ChartPermissionId
				item.IcoLink = v2.IcoLink
				item.List = make([]string, 0)
				list = append(list, item)
			}
		}
	}
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 期数列表
// @Description 获取期数列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Success 200 {object} cygx.CygxReportSelectionPeriodsListRep
// @router /reportSelection/listPeriods [get]
func (this *ReportSelectionController) ListPeriods() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	var startSize int
	if pageSize <= 0 {
		pageSize = 1000
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)
	var condition string
	var pars []interface{}

	total, err := cygx.GetCygxReportSelection(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	list, err := cygx.GetReportSelectionListPeriods(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	for k, v := range list {
		if v.Periods != "" {
			list[k].InheritPeriodsName = "第" + v.Periods + "期"
		}
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(cygx.CygxReportSelectionPeriodsListRep)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 阅读明细下载
// @Description 获取阅读明细下载接口
// @Param   ArticleId   query   int  true        "文章ID"
// @Param   Source      query   int  true        "来源 1：报告精选、2：路演精华、3：本周研究汇总、4：上周纪要汇总"
// @Success 200 导出成功
// @router /reportSelection/articleHistoryExport [get]
func (this *ReportSelectionController) ArticleHistoryExport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	articleId, _ := this.GetInt("ArticleId")
	source, _ := this.GetInt("Source")

	resp := new(cygx.CanDownload)
	adminInfo, errAdmin := system.GetSysUserById(AdminUser.AdminId)
	if errAdmin != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errAdmin.Error()
		return
	}
	if adminInfo.Role == "admin" || adminInfo.Role == "researcher" || adminInfo.RealName == "汪洋" {
		resp.IsCanDownload = true
	}

	var condition string
	if resp.IsCanDownload == false {
		//权益申请销售只能看到自己名下的客户的申请
		companyIds, err := cygxService.GetAdminLookUserCompanyIds(AdminUser)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，GetAdminLookUserCompanyIds Err:" + err.Error()
			return
		}
		var companyIdstr []string
		for _, v := range companyIds {
			companyIdstr = append(companyIdstr, strconv.Itoa(v))
		}
		condition = ` AND h.company_id IN (` + strings.Join(companyIdstr, ",") + `)`
	}

	condition += `  AND h.company_id != ` + strconv.Itoa(utils.HZ_COMPANY_ID) // 过滤弘则来源
	var list []*cygx.ArticleHistoryRep
	var err error
	var table string
	//"来源 1：报告精选、2：路演精华、3：本周研究汇总、4：上周纪要汇总"
	//报告类型，bgjx:报告精选、bzyjhz:本周研究汇总、szjyhz:上周纪要汇总
	if source != 2 {
		if source == 1 {
			table = "cygx_report_selection"
			condition += ` AND  h.report_type = 'bgjx'`
		} else if source == 3 {
			table = "cygx_research_summary"
			condition += ` AND h.report_type = 'bzyjhz'`
		} else {
			table = "cygx_minutes_summary"
			condition += ` AND h.report_type = 'szjyhz'`
		}
		list, err = cygx.GetReportSelectionHistoryList(articleId, condition)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
	} else {
		table = "cygx_article"
		list, err = cygx.GetArticleHistoryListOld(articleId, condition)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
	}
	//根据不同类型获取不同报告的详情
	articleInfo, err := cygx.GetArticleInfoByIdAndTable(table, articleId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取报告详情失败，Err:" + err.Error()
		return
	}
	fmt.Println(articleInfo)
	//

	//创建excel
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}
	style.Alignment = alignment
	style.ApplyAlignment = true
	sheet, err := xlsxFile.AddSheet("名单")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	//标头
	rowTitle := sheet.AddRow()
	cellA := rowTitle.AddCell()
	cellA.Value = "姓名"
	cellB := rowTitle.AddCell()
	cellB.Value = "手机号"
	cellC := rowTitle.AddCell()
	cellC.Value = "公司名称"
	cellD := rowTitle.AddCell()
	cellD.Value = "所属权益销售"
	cellF := rowTitle.AddCell()
	cellF.Value = "阅读时间"

	for _, item := range list {
		row := sheet.AddRow()
		cellA := row.AddCell()
		cellA.Value = item.RealName
		cellB := row.AddCell()
		cellB.Value = item.Mobile
		cellC := row.AddCell()
		cellC.Value = item.CompanyName
		cellD := row.AddCell()
		cellD.Value = item.SellerName
		cellF := row.AddCell()
		cellF.Value = item.CreateTime
	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	//randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := articleInfo.Title + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		//os.Remove(downLoadnFilePath)
	}()
	br.Success = true
	br.Ret = 200
	br.Msg = "导出成功"
}

// @Title 通过标的ID获取相关连的产文章信息
// @Description 通过标的ID获取相关连的产文章信息接口
// @Param   IndustrialSubjectId   query   int  true       "标的id "
// @Success 200 {object} cygx.OverviewArticle
// @router /reportSelection/getArticle [get]
func (this *ReportSelectionController) GetArticle() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	industrialSubjectId, _ := this.GetInt("IndustrialSubjectId")
	if industrialSubjectId < 1 {
		br.Msg = "请输入标的ID"
		return
	}
	detailSubjecj, err := cygx.GetIndustrialSubjectDetailById(industrialSubjectId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}
	resp := new(cygx.OverviewArticle)
	if detailSubjecj != nil {
		var pars []interface{}
		conditionArticle := `  AND type_name = '综述报告'  AND  stock LIKE ? `
		subjectName := "%" + detailSubjecj.SubjectName + "%"
		pars = append(pars, subjectName)
		articleList, err := cygx.GetCygxArticleList(conditionArticle, pars, 0, 10)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "GetCygxArticleList，Err:" + err.Error()
			return
		}
		//一对一精准匹配
		for _, v := range articleList {
			sliceSubjects := strings.Split(v.Stock, "/")
			if len(sliceSubjects) > 0 {
				for _, vSubject := range sliceSubjects {
					sliceKuohao := strings.Split(vSubject, "(")           //过滤括号
					sliceXiahuaxian := strings.Split(sliceKuohao[0], "-") //过滤下划线
					subject := sliceXiahuaxian[0]
					if subject == detailSubjecj.SubjectName {
						resp.ArticleId = v.ArticleId
						resp.Title = v.Title
						continue
					}
				}
			}
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title   报告精选的可见范围修改
// @Description   报告精选的可见范围修改接口
// @Param	request	body cygx.ResearchSummaryId true "type json string"
// @Success 200 操作成功
// @router /reportSelection/visibleRange [post]
func (this *ReportSelectionController) VisibleRange() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	var req cygx.ResearchSummaryId
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	articleId := req.ArticleId
	detail, err := cygx.GetCygxReportSelectionInfoById(articleId)
	if err != nil {
		br.Msg = "内容不存在"
		br.ErrMsg = "操作失败,Err:" + err.Error()
		return
	}
	item := new(cygx.CygxReportSelectionRep)
	item.ArticleId = articleId
	if detail.VisibleRange == 0 {
		item.VisibleRange = 1
		item.AdminId = AdminUser.AdminId
		item.AdminName = AdminUser.RealName
		if detail.IsSendWxMsg == 0 {
			cygxService.DoThisWeekLastWeekWxTemplateMsg(detail.Title, detail.PublishDate, detail.ProductDescription, req.ArticleId, 1)
		}
	} else {
		item.AdminId = detail.AdminId
		item.AdminName = detail.AdminName
		item.VisibleRange = 0
	}
	err = cygx.ReportSelectionVisibleRange(item)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败,Err:" + err.Error()
		return
	}
	go cygxService.UpdateReportSelectionResourceData(articleId) //首页最新页面数据逻辑处理 V11.1.1
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.IsAddLog = true
}

// @Title  报告精选内容详情
// @Description  报告精选内容详情接口
// @Param   ArticleId   query   int  true       "报告Id"
// @Success Ret=200 {object} cygx.DetailCygxReportSelectionRep
// @router /reportSelection/history [get]
func (this *ReportSelectionController) History() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	var errArt error
	detail := new(cygx.CygxReportSelectionRep)
	articleId, _ := this.GetInt("ArticleId")

	detail, errArt = cygx.GetCygxReportSelectionInfoById(articleId)
	if errArt != nil {
		br.Msg = "内容不存在"
		br.ErrMsg = "内容不存在,Err:" + errArt.Error()
		return
	}
	articleId = detail.ArticleId
	resp := new(cygx.HistoryReportSelectionRep)

	permissionNameMap, err := services.GetPermissionNameMap()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败 GetPermissionNameMap，Err:" + err.Error()
		return
	}

	listSelectionLog, err := cygx.GetReportSelectionlogListAll(articleId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "GetReportSelectionlogListAll，Err:" + err.Error()
		return
	}

	for k, v := range listSelectionLog {
		listSelectionLog[k].PermissionName = permissionNameMap[v.ChartPermissionId]
	}
	//获取标的的点击次数
	listSelectionSubjectHistory, err := cygx.GetCygxReportSelectionSubjectHistoryList(articleId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "GetCygxReportSelectionSubjectHistoryList，Err:" + err.Error()
		return
	}
	mapSubjectHistory := make(map[string]int)
	for _, v := range listSelectionSubjectHistory {
		mapSubjectHistory[v.IndustrialSubjectId]++
	}

	//排序方式修改
	permissionNameList := []*cygx.HistoryReportSelectionChart{{ChartPermissionName: "消费"}, {ChartPermissionName: "医药"}, {ChartPermissionName: "科技"}, {ChartPermissionName: "智造"}}
	for _, v := range permissionNameList {
		v.List = make([]*cygx.HistoryReportSelectionLogResp, 0)
		for _, v2 := range listSelectionLog {
			if v.ChartPermissionName == v2.PermissionName {
				item := new(cygx.HistoryReportSelectionLogResp)
				item.SubjectName = v2.SubjectName
				item.IndustrialSubjectId = v2.IndustrialSubjectId
				item.IsNew = v2.IsNew
				item.Count = mapSubjectHistory[v2.IndustrialSubjectId]
				resp.Count += item.Count
				v.List = append(v.List, item)
			}
		}
	}
	resp.List = permissionNameList
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title  报告精选申请记录
// @Description  报告精选申请记录接口
// @Param   ArticleId   query   int  true       "报告Id"
// @Success Ret=200 {object} cygx.DetailCygxReportSelectionRep
// @router /reportSelection/tarryList [get]
func (this *ReportSelectionController) RarryList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	articleId, _ := this.GetInt("ArticleId")
	resp := new(cygx.CygxReportSelectionLogApplyListResp)
	var condition string
	var pars []interface{}
	condition = " AND article_id = ? ORDER  BY create_time DESC  "
	pars = append(pars, articleId)
	list, err := cygx.GetCygxReportSelectionLogApplyRespList(condition, pars, 0, 0)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}
	if len(list) == 0 {
		list = make([]*cygx.CygxReportSelectionLogApplyResp, 0)
	}
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}
