package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/services"
	"hongze/hongze_cygx/utils"
	"strconv"
	"strings"
	"time"
)

// 报告
type ReportSelectionController struct {
	BaseAuthController
}

// @Title 获取报告精选详情
// @Description 获取报告精选详情接口
// @Param   ArticleId   query   int  true       "报告ID"
// @Param   IsBestNew   query   bool  false       "是否获取最新的一篇报告"
// @Success 200 {object} models.ReportSelectionLetailResp
// @router /detail [get]
func (this *ReportSelectionController) Detail() {
	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
	articleId, _ := this.GetInt("ArticleId")
	activityId, _ := this.GetInt("ActivityId")
	isBestNew, _ := this.GetBool("IsBestNew")
	if activityId > 0 && articleId == 0 {
		articleId = activityId
	}
	if articleId == 0 || isBestNew {
		isBestNew = true
		if isBestNew {
			tbdb := "cygx_report_selection"
			condition := ` AND publish_status = 1    `
			var pars []interface{}
			list, err := models.GetReportSelectionListPublic(condition, "1", tbdb, pars, 0, 1)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取失败，Err:" + err.Error()
				return
			}
			for _, v := range list {
				articleId = v.ArticleId
			}
		}
	}
	if articleId < 1 {
		br.Msg = "获取信息失败"
		br.ErrMsg = "报告ID错误" + strconv.Itoa(articleId)
		return
	}

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

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

	resp := new(models.ReportSelectionLetailResp)
	//判断用户权限
	hasPermission, err := services.GetUserhasPermissionReportSelection(user)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取用户权限信息失败,Err:" + err.Error()
	}
	detail, err := models.GetCygxReportSelectionInfoById(articleId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "报告不存在,Err:" + err.Error() + "articleId：" + strconv.Itoa(articleId)
		return
	}
	//未设置全部可见的只能给弘则内部查看
	if detail.VisibleRange == 1 || user.CompanyId == utils.HZ_COMPANY_ID {
		resp.IsShow = true
	}
	resp.HasPermission = hasPermission
	if !resp.IsShow {
		br.Ret = 201
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
		return
	}
	if hasPermission != 1 || !resp.IsShow {
		resp.Detail = detail
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
		return
	}
	if detail.ReportLink != "" {
		articleIdLink, _ := services.GetReportLinkToArticleid(detail.ReportLink)
		detail.CeLueArticleId = articleIdLink
	}
	articleStockMap, _ := services.GetArticleStockMap()
	detail.PublishDate = utils.StrTimeToTime(detail.PublishDate).Format("2006-01-02")
	existMap := make(map[int]int)
	var items []*models.ReportSelectionChartPermission
	var itemsSubject []*models.ReportSelectionChartLogPermission
	listLog, err := models.GetReportSelectionlogListAll(articleId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取子类信息失败，Err:" + err.Error()
		return
	}
	detail.VideoPlaySeconds = utils.Mp3Time(detail.VideoPlaySeconds)
	//获取行业核心逻辑汇总
	listChartLog, err := models.GetCygxReportSelectionChartLogRepList(articleId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	mapChartLog := make(map[string]string)
	for _, v := range listChartLog {
		mapChartLog[v.ChartPermissionName] = v.BodyChartSummary
	}
	for _, v := range listLog {
		v.PermissionName = PermissionNameMap[v.ChartPermissionId]
		item := new(models.ReportSelectionChartPermission)
		itemSubject := new(models.ReportSelectionChartLogPermission)
		itemSubject.PermissionName = v.PermissionName
		if existMap[v.ChartPermissionId] == 0 {
			//item.PermissionName = v.PermissionName + "领域深度报告和调研"
			item.PermissionName = v.PermissionName
			item.IcoLink = v.IcoLink
			listSonLog, err := models.GetReportSelectionlogSonListAll(articleId, v.ChartPermissionId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "获取信息失败"
				br.ErrMsg = "获取信息失败,Err:" + err.Error()
				return
			}
			for k2, v2 := range listSonLog {
				if v2.IndustrialManagementId != "" {
					listIndustrial, err := models.GetIndustrialByIds(v2.IndustrialManagementId)
					if err != nil && err.Error() != utils.ErrNoRow() {
						br.Msg = "获取信息失败"
						br.ErrMsg = "获取信息失败,Err:" + err.Error()
						return
					}
					//后台如果勾了隐藏那么这里就不展示  V11.3  2023-08-17
					if listSonLog[k2].IsShowOverviewArticle == 1 {
						listSonLog[k2].OverviewArticleId = articleStockMap[v2.SubjectName]
					} else {
						listSonLog[k2].OverviewArticleId = 0
					}
					listSonLog[k2].List = listIndustrial
					//listSonLog[k2].IsShowApplyButton = true
					if v2.SubjectName == "" {
						v2.ShowName = v2.IndustrialManagementNames
					} else {
						v2.ShowName = v2.SubjectName
					}
				}
				if v2.Label != "" {
					v2.CompanyLabel = strings.Split(v2.Label, "{|}")
				}
				if v2.ThirdName != "" {
					v2.ShowName = v2.ThirdName
				}
				subjectItem := new(models.ReportSelectionChartLogSubjectName)
				subjectItem.SubjectName = v2.SubjectName
				subjectItem.IsNew = v2.IsNew
				subjectItem.IndustrialSubjectId = v2.IndustrialSubjectId
				subjectItem.IndustrialManagementId, _ = strconv.Atoi(v2.IndustrialManagementId)
				subjectItem.IndustrialManagementName = v2.IndustrialManagementNames
				subjectItem.ThirdId = v2.ThirdId
				if v2.ThirdName != "" {
					subjectItem.SubjectName = v2.ThirdName
				} else {
					if subjectItem.SubjectName == "" {
						subjectItem.SubjectName = subjectItem.IndustrialManagementName
					}
				}
				subjectItem.Md5String = utils.MD5(fmt.Sprint("IN_ID", v2.IndustrialManagementId, "S_ID", v2.IndustrialSubjectId, "T_ID", v2.ThirdId))
				v2.Md5String = subjectItem.Md5String
				itemSubject.ListSubject = append(itemSubject.ListSubject, subjectItem)
				//itemSubject.ListSubject = append(itemSubject.ListSubject, &models.ReportSelectionChartLogSubjectName{SubjectName: v2.SubjectName, IsNew: v2.IsNew, IndustrialSubjectId: v2.IndustrialSubjectId})
			}
			item.BodyChartSummary = mapChartLog[v.PermissionName]
			item.List = listSonLog
			item.PermissionName = PermissionNameMap[v.ChartPermissionId]
			item.IcoLink = PermissionIcoMap[v.ChartPermissionId]
			items = append(items, item)
			itemsSubject = append(itemsSubject, itemSubject)
			//itemLogs = make([]*models.CygxReportSelectionLogDetail, 0)
		}
		existMap[v.ChartPermissionId] = v.ChartPermissionId
	}
	resp.List = items
	resp.ListPermissionSubject = itemsSubject
	resp.Detail = detail
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 标的点击记录
// @Description 标的点击记录接口
// @Param	request	body models.AddCygxReportSelectionSubjectHistoryReq true "type json string"
// @router /click/history [post]
func (this *ReportSelectionController) ClickHistory() {
	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 req models.AddCygxReportSelectionSubjectHistoryReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ArticleId <= 0 {
		br.Msg = "文章不存在"
		br.ErrMsg = "文章不存在，文章ID错误"
		return
	}
	if req.IndustrialSubjectId+req.IndustrialManagementId+req.ThirdId <= 0 {
		br.Msg = "标的ID不存在"
		br.ErrMsg = "产业或标的ID不存在"
		return
	}
	item := models.CygxReportSelectionSubjectHistory{
		UserId:                 user.UserId,
		ArticleId:              req.ArticleId,
		CreateTime:             time.Now(),
		ModifyTime:             time.Now(),
		Mobile:                 user.Mobile,
		Email:                  user.Email,
		CompanyId:              user.CompanyId,
		CompanyName:            user.CompanyName,
		IndustrialSubjectId:    req.IndustrialSubjectId,
		IndustrialManagementId: req.IndustrialManagementId,
		ThirdId:                req.ThirdId,
		RegisterPlatform:       utils.REGISTER_PLATFORM,
	}
	err = models.AddCygxReportSelectionSubjectHistory(&item)
	if err != nil {
		br.Msg = "记录失败"
		br.ErrMsg = "记录失败,Err:" + err.Error()
		return
	}
	go services.GetReportSelectionLabelName(req, user.UserId) //记录用户在重点公司单独点了某一个标签
	br.Ret = 200
	br.Success = true
	br.Msg = "记录成功"
}

// @Title 上传文章阅读时间
// @Description 上传文章阅读时间接口
// @Param  request	body models.AddStopTimeRep true "type json string"
// @Success 200 {object} models.ArticleDetailResp
// @router /addStopTime [post]
func (this *ReportSelectionController) AddStopTime() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	user := this.User
	if user == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	var req models.AddReportSelectionStopTimeRep
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	uid := user.UserId
	articleId := req.ArticleId
	stopTime := req.StopTime
	outType := req.OutType
	source := req.Source
	var reportType string
	var tableName, label string
	if source == 1 {
		reportType = "bgjx"
		tableName = "cygx_report_selection"
		label = "重点推荐"
	} else if source == 2 {
		reportType = "bzyjhz"
		tableName = "cygx_research_summary"
		label = "本周研究汇总"
	} else if source == 3 {
		reportType = "szjyhz"
	}
	var hasPermission int
	if source == 1 {
		hasPermission, err = services.GetUserhasPermissionReportSelection(user)
	} else {
		hasPermission, err = services.GetUserhasPermission(user)
	}
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取用户权限信息失败,Err:" + err.Error()
	}

	if hasPermission == 1 {
		historyRecord := new(models.CygxReportHistoryRecord)
		historyRecord.UserId = uid
		historyRecord.ArticleId = articleId
		historyRecord.CreateTime = time.Now().Add(-time.Second * time.Duration(stopTime))
		historyRecord.Mobile = user.Mobile
		historyRecord.Email = user.Email
		historyRecord.CompanyId = user.CompanyId
		historyRecord.CompanyName = user.CompanyName
		historyRecord.StopTime = stopTime
		historyRecord.OutType = outType
		historyRecord.ReportType = reportType
		historyRecord.RegisterPlatform = utils.REGISTER_PLATFORM
		sellerItem, err := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取销售信息失败,Err:" + err.Error()
			return
		}
		historyRecord.RealName = user.RealName
		if sellerItem != nil {
			historyRecord.SellerName = sellerItem.RealName
		}
		go services.AddCygxReportHistoryRecord(historyRecord)
		if tableName != "" {
			go services.ReportSelectionWxUserRaiLabelRedisAdd(articleId, uid, historyRecord.CreateTime, tableName, label)
		}
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// @Title 获取报告精选列表
// @Description 获取报告精选列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Success 200 {object} models.ReportSelectionLetailResp
// @router /list [get]
func (this *ReportSelectionController) List() {
	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
	}
	resp := new(models.CygxReportSelectionListPublicRep)
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")

	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{}
	condition += ` AND art.publish_status = 1 AND article_id >= 16 `
	total, err := models.GetCygxReportSelectionCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	condition += "	ORDER BY art.publish_date  DESC "
	list, err := models.GetReportSelectionList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	var articleIdArr []int
	for _, v := range list {
		v.PublishDate = utils.TimeRemoveHms2(v.PublishDate)
		articleIdArr = append(articleIdArr, v.ArticleId)
	}

	lenarticleIdArr := len(articleIdArr)
	maplabel := make(map[int]string)
	if lenarticleIdArr > 0 {
		condition = ""
		pars = make([]interface{}, 0)
		condition = ` AND is_new = 1  AND article_id IN (` + utils.GetOrmInReplace(lenarticleIdArr) + `)`
		pars = append(pars, articleIdArr)
		listLog, err := models.GetCygxReportSelectionLog(condition, pars, 0, 9999)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，GetCygxReportSelectionLogErr:" + err.Error()
			return
		}
		for _, v := range listLog {
			maplabel[v.ArticleId] += v.SubjectName + ","
		}
	}
	for _, v := range list {
		v.SubjectName = strings.TrimRight(maplabel[v.ArticleId], ",")
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 报告精选申请路演
// @Description 报告精选申请路演
// @Param	request	body cygx.CygxBannerIdReq true "type json string"
// @Success 200 Ret=200 提交成功
// @router /report_selection_log/apply [post]
func (this *ReportSelectionController) ReportSelectionLogApply() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	user := this.User
	if user == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	var req models.CygxReportSelectionLogApplyReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	articleId := req.ArticleId
	subjectName := req.SubjectName

	var condition string
	var pars []interface{}
	condition += ` AND  article_id = ? AND subject_name = ? AND user_id = ?  `
	pars = append(pars, articleId, subjectName, user.UserId)
	totalApply, err := models.GetCygxReportSelectionLogApplyCount(condition, pars)
	if err != nil {
		br.Msg = "申请失败！"
		br.ErrMsg = "申请失败，Err:" + err.Error()
		return
	}
	if totalApply > 0 {
		br.Msg = "您已提交过此公司的路演申请，请等待销售与您联系！"
		return
	}

	logDetail, err := models.GetCygxReportSelectionLogDetail(articleId, subjectName)
	if err != nil {
		br.Msg = "申请失败！"
		br.ErrMsg = "申请失败，Err:" + err.Error()
		return
	}

	item := new(models.CygxReportSelectionLogApply)
	item.UserId = user.UserId
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	item.Mobile = user.Mobile
	item.Email = user.Email
	item.CompanyId = user.CompanyId
	item.CompanyName = user.CompanyName
	item.ArticleId = logDetail.ArticleId
	item.SubjectName = logDetail.SubjectName
	item.IndustrialSubjectId = logDetail.IndustrialSubjectId
	item.RegisterPlatform = utils.REGISTER_PLATFORM
	sellerItem, err := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return
	}
	item.RealName = user.RealName
	if sellerItem != nil {
		item.SellerName = sellerItem.RealName
	}
	_, err = models.AddCygxReportSelectionLogApply(item)
	if err != nil {
		br.Msg = "申请失败"
		br.ErrMsg = "申请失败，Err:" + err.Error()
		return
	}
	go services.SendCygxReportSelectionLogApplyTemplateMsg(user, logDetail.SubjectName)
	br.Ret = 200
	br.Success = true
	br.Msg = "记录成功"
}
