package report

import (
	"encoding/json"
	logger "eta/eta_mini_ht_api/common/component/log"
	"eta/eta_mini_ht_api/common/exception"
	"eta/eta_mini_ht_api/common/utils/page"
	"eta/eta_mini_ht_api/controllers"
	reportService "eta/eta_mini_ht_api/domian/report"
	"eta/eta_mini_ht_api/service/report"
	"eta/eta_mini_ht_api/service/user"
)

type ReportController struct {
	controllers.ListController
}

// Search 搜索报告列表
// @Description 搜索报告列表
// @Success 200 {object}
// @router /search [get]
func (r *ReportController) Search(key string) {
	controllers.Wrap(&r.BaseController, func() (result *controllers.WrapData, err error) {
		result = r.InitWrapData("分页搜索报告列表失败")
		if key == "" {
			err = exception.New(exception.SearchKeyEmptyError)
			r.FailedResult("分页搜索报告列表失败", result)
			return
		}
		pageRes := page.Page{
			Current:  r.PageInfo.Current,
			PageSize: r.PageInfo.PageSize,
		}
		if r.PageInfo.LatestId == 0 {
			pageRes.Total, pageRes.LatestId = report.SearchMaxReportId(key)
			r.PageInfo.LatestId = pageRes.LatestId
			r.PageInfo.Total = pageRes.Total
		} else {
			pageRes.LatestId = r.PageInfo.LatestId
			pageRes.Total = r.PageInfo.Total
		}
		pageRes.TotalPage = page.TotalPages(pageRes.Total, pageRes.PageSize)
		list := make([]reportService.ReportDTO, 0)
		if pageRes.LatestId > 0 {
			list, err = report.SearchReportList(key, r.PageInfo)
			if err != nil {
				r.FailedResult("分页搜索报告列表失败", result)
				return
			}
		}
		reports := new(page.PageResult)
		reports.Data = list
		reports.Page = pageRes
		r.SuccessResult("分页搜索报告列表成功", reports, result)
		return
	})
}

// List 获取报告列表
// @Description 获取报告列表
// @Success 200 {object}
// @router /list [get]
func (r *ReportController) List(permissionIds string) {
	controllers.Wrap(&r.BaseController, func() (result *controllers.WrapData, err error) {
		result = r.InitWrapData("分页查询报告列表失败")
		pageRes := page.Page{
			Current:  r.PageInfo.Current,
			PageSize: r.PageInfo.PageSize,
		}
		permissionIdList, err := r.TransPermissionIds(permissionIds)
		if err != nil {
			logger.Error("品种列表解析错误:%v", err)
			r.FailedResult("分页查询报告列表失败", result)
			err = exception.New(exception.QueryReportPageFailed)
			return
		}
		var reportOrgIds map[string][]int
		if r.PageInfo.LatestId == 0 {
			pageRes.Total, pageRes.LatestId, reportOrgIds = report.GetTotalPageCountByPermissionIds(permissionIdList)
			r.PageInfo.LatestId = pageRes.LatestId
		} else {
			pageRes.LatestId = r.PageInfo.LatestId
			pageRes.Total = r.PageInfo.Total
		}
		pageRes.TotalPage = page.TotalPages(pageRes.Total, pageRes.PageSize)
		if len(permissionIdList) > 0 && len(reportOrgIds) == 0 {
			logger.Info("没有搜索到相关品种的报告，返回空")
			reports := new(page.PageResult)
			reports.Data = []reportService.ReportDTO{}
			reports.Page = pageRes
			r.SuccessResult("查询报告列表成功", reports, result)
			return
		}
		all := false
		if len(permissionIdList) == 0 && len(reportOrgIds) > 0 {
			err = exception.New(exception.UnknownError)
			r.FailedResult("查询报告列表失败", result)
		}
		if len(permissionIdList) == 0 && len(reportOrgIds) == 0 {
			all = true
		}
		list, err := report.GetReportPage(r.PageInfo, reportOrgIds, all)
		if err != nil {
			r.FailedResult("分页查询报告列表失败", result)
			return
		}
		reports := new(page.PageResult)
		reports.Data = list
		reports.Page = pageRes
		r.SuccessResult("查询报告列表成功", reports, result)
		return
	})
}

// HotRanked @Title 获取本周最热的报告列表
// @Description 获取本周最热的报告列表
// @Success 200 {object}
// @router /hotRankedList [get]
func (r *ReportController) HotRanked(permissionIds string, limit int) {
	controllers.Wrap(&r.BaseController, func() (result *controllers.WrapData, err error) {
		if limit <= 0 {
			limit = 3
		}
		result = r.InitWrapData("获取本周最热报告列表失败")
		list, err := report.GetRandedReportByWeeklyHot(limit)
		//二级品种
		permissionIdList, err := r.TransPermissionIds(permissionIds)
		if err != nil {
			logger.Error("品种列表解析错误:%v", err)
			r.FailedResult("分页查询报告列表失败", result)
			err = exception.New(exception.QueryReportPageFailed)
			return
		}
		filterList := make([]report.HotRankedReport, 0)
		if len(permissionIdList) > 0 {
			for _, item := range list {
				for _, permissionId := range permissionIdList {
					if _, ok := item.SecondPermissions[permissionId]; ok {
						filterList = append(filterList, item)
						break
					}
				}
			}
		} else {
			filterList = list
		}
		if err != nil {
			r.FailedResult("获取本周最热报告列表成功", result)
			return
		}
		r.SuccessResult("获取本周最热报告列表成功", filterList, result)
		return
	})
}

// PublishRanked @Title 获取最新发布的报告列表
// @Description 获取最新发布的报告列表
// @Success 200 {object}
// @router /publishRankedList [get]
func (r *ReportController) PublishRanked(limit int, week bool) {
	controllers.Wrap(&r.BaseController, func() (result *controllers.WrapData, err error) {
		result = r.InitWrapData("获取最新发布报告列表失败")
		if limit <= 0 {
			limit = 3
		}
		//获取最新的报告列表
		list, err := report.GetRandedReportByPublishTimeWeekly(limit, week)
		if err != nil {
			r.FailedResult("获取最新发布报告列表失败", result)
			return
		}

		r.SuccessResult("获取最新发布报告列表成功", list, result)
		return
	})
}

// GetPermissions  @Title 获取品种列表
// @Description 获取最新发布的报告列表
// @Success 200 {object}
// @router /permissionList [get]
func (r *ReportController) GetPermissions() {
	controllers.Wrap(&r.BaseController, func() (result *controllers.WrapData, err error) {
		result = r.InitWrapData("获取品种列表失败")
		//获取最新的报告列表
		json, err := report.GetPermissionList()
		if err != nil {
			r.FailedResult("获取品种列表失败", result)
			return
		}
		r.SuccessResult("获取最新发布报告列表成功", json.Children, result)
		return
	})
}

type RecordCountReq struct {
	ReportId   int         `json:"reportId"`
	IpAddress  string      `json:"ipAddress"`
	Location   string      `json:"location"`
	Referer    string      `json:"referer"`
	Additional interface{} `json:"additional"`
}

// Count 获取品种列表
// @Description 获取最新发布的报告列表
// @Success 200 {object}
// @router /count [post]
func (r *ReportController) Count() {
	controllers.Wrap(&r.BaseController, func() (result *controllers.WrapData, err error) {
		result = r.InitWrapData("研报点击记录失败")
		var userInfo user.User
		userInfo = r.Data["user"].(user.User)
		recordReq := new(RecordCountReq)
		if recordReq.ReportId <= 0 {
			logger.Error("研报点击记录失败,reportId不能为空")
			r.FailedResult("研报点击记录失败", result)
			err = exception.New(exception.ReportRecordClickCountFailed)
			return
		}
		r.GetPostParams(recordReq)
		record := convertToRecordCount(recordReq)
		record.UserId = userInfo.Id
		record.Mobile = userInfo.Mobile
		err = report.CountReport(record)
		if err != nil {
			r.FailedResult("研报点击记录失败", result)
			err = exception.New(exception.ReportRecordClickCountFailed)
			return
		}
		r.SuccessResult("研报点击记录成功", nil, result)
		return
	})
}

// GetReport 获取研报详情
// @Description 获取研报详情
// @Success 200 {object}
// @router /report [get]
func (r *ReportController) GetReport(reportId int) {
	controllers.Wrap(&r.BaseController, func() (result *controllers.WrapData, err error) {
		result = r.InitWrapData("获取研报详情失败")
		reportDetail, err := report.GetReportById(reportId)
		if err != nil {
			r.FailedResult("获取研报详情失败", result)
			err = exception.New(exception.GetReportFailed)
			return
		}
		r.SuccessResult("获取研报详情成功", reportDetail, result)
		return
	})
}
func convertToRecordCount(req *RecordCountReq) report.RecordCount {
	additionStr, _ := json.Marshal(req.Additional)
	return report.RecordCount{
		ReportId:   req.ReportId,
		IpAddress:  req.IpAddress,
		Location:   req.Location,
		Referer:    req.Referer,
		Additional: string(additionStr),
	}
}
