package yb

import (
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/yb"
	ybResp "hongze/hz_crm_api/models/yb/response"
	ybService "hongze/hz_crm_api/services/yb"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

type LikeController struct {
	controllers.BaseAuthController
}

// ReportList
// @Title 获取已被点赞的报告列表
// @Description 获取已被点赞的报告列表
// @Param   SortParam         query   string    false		"排序关键词：LikeNum"
// @Param   SortType          query   string    false		"排序顺序：asc、desc"
// @Param   PageSize          query   string    false      "每页展示的记录数"
// @param   CurrentIndex      query   string    false      "页码"
// @Success 200 {object}  ybResp.LikeReportListResp
// @router /like/report/list [get]
func (this *LikeController) ReportList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser is Empty"
		br.Ret = 408
		return
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	//todo 判断查询权限
	brMsg, brErrMsg := ybService.CheckCommentPermission(sysUser.AdminId)
	if brMsg != "" {
		br.Msg = brMsg
		br.ErrMsg = brErrMsg
		return
	}
	orderStr := ""
	orderType := ""
	reqSortParam := this.GetString("SortParam", "")
	if reqSortParam != "" {

	}
	reqSortType := this.GetString("SortType")
	if reqSortType != "" && reqSortParam == "LikeNum" {
		orderType = reqSortType
	}
	likeList, err := yb.GetLikeReportIds(orderType)
	if err != nil {
		br.Msg = "获取报告ID失败！"
		br.ErrMsg = "获取报告ID失败，Err:" + err.Error()
		return
	}
	if len(likeList) == 0 {
		page := paging.GetPaging(currentIndex, pageSize, 0)
		data := &ybResp.LikeReportListResp{
			Paging: page,
		}
		br.Ret = 200
		br.Success = true
		br.Msg = "操作成功"
		br.Data = data
		return
	}
	reportIds := "0"
	reportChapterIds := "0"
	reportChapterConcat := ""
	LikeNumMap := make(map[string]int)
	LikeTimeMap := make(map[string]time.Time)
	dayWeekReportIds := ""
	for _, v := range likeList {
		reportIdStr := strconv.Itoa(v.ReportId)
		reportChapterIdStr := strconv.Itoa(v.ReportChapterId)
		// 过滤晨报和周报报告ID
		if v.ReportChapterId == 0 {
			reportIds += "," + reportIdStr
		}
		// 过滤章节ID为0的值
		if reportChapterIdStr != "0" {
			dayWeekReportIds += "," + reportIdStr
			reportChapterIds += "," + reportChapterIdStr
		}

		concat := reportIdStr + "-" + reportChapterIdStr
		reportChapterConcat += `,"` + concat + `"`
		LikeNumMap[concat] = v.LikeNum
		LikeTimeMap[concat] = v.ModifyTime
	}
	if reportChapterConcat != "" {
		reportChapterConcat = strings.Trim(reportChapterConcat, ",")
	}
	//根据入参判断是否需要按照点赞数排序
	if reqSortParam == "LikeNum" {
		orderStr = reportChapterConcat
	}

	reportList, err := models.GetLikeReportByReportIdReportChapterId(reportIds, reportChapterIds, orderStr, startSize, pageSize)
	if err != nil {
		br.Msg = "获取报告失败！"
		br.ErrMsg = "获取报告失败，Err:" + err.Error()
		return
	}

	//查询晨报周报的总标题
	dayWeekTitleMap := make(map[int]string)
	if dayWeekReportIds != "" {
		dayWeekReportIds = strings.Trim(dayWeekReportIds, ",")
		dayWeekReports, tErr := models.GetSimpleReportByIds(dayWeekReportIds)
		if tErr != nil {
			br.Msg = "获取报告失败！"
			br.ErrMsg = "获取报告失败，Err:" + tErr.Error()
			return
		}
		for _, v := range dayWeekReports {
			dayWeekTitleMap[v.Id] = v.Title
		}
	}

	var list []*ybResp.LikeReportListItem
	for _, v := range reportList {
		tmp := new(ybResp.LikeReportListItem)
		concat := strconv.Itoa(v.ReportId) + "-" + strconv.Itoa(v.ReportChapterId)
		tmp.ReportId = v.ReportId
		tmp.ReportChapterId = v.ReportChapterId
		tmp.ClassifyIdFirst = v.ClassifyIdFirst
		tmp.ClassifyNameFirst = v.ClassifyNameFirst
		tmp.PublishTime = v.PublishTime.Format(utils.FormatDateTime)
		// todo 晨周报需要展示大标题
		if tmp.ReportChapterId > 0 {
			if t, ok := dayWeekTitleMap[v.ReportId]; ok {
				tmp.Title = t
			}
		} else {
			tmp.Title = v.Title
		}

		tmp.ReportChapterTypeName = v.ReportChapterTypeName
		if t, ok := LikeTimeMap[concat]; ok {
			tmp.ModifyTime = t.Format(utils.FormatDateTime)
		}
		if n, ok := LikeNumMap[concat]; ok {
			tmp.LikeNum = n
		}
		list = append(list, tmp)
	}
	// 获取列表分页总数
	total, err := models.GetLikeReportTotalByReportIdReportChapterId(reportIds, reportChapterIds)
	if err != nil {
		br.Msg = "获取留言列表总数失败！"
		br.ErrMsg = "获取留言列表总数失败，Err:" + err.Error()
		return
	}
	page := paging.GetPaging(currentIndex, pageSize, int(total))
	data := &ybResp.LikeReportListResp{
		List:   list,
		Paging: page,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.Data = data
	return
}

// List
// @Title 获取报告的点赞列表
// @Description 获取报告的点赞列表
// @Param   ReportId           query   string    true		"报告ID"
// @Param   ReportChapterId    query   string    true		"报告章节ID"
// @Param   PageSize          query   string    false      "页码"
// @param   CurrentIndex      query   string    false      "每页展示的记录数"
// @Success 200 {object}  ybResp.LikeListResp
// @router /like/list [get]
func (this *LikeController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser is Empty"
		br.Ret = 408
		return
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	//todo 判断查询权限
	brMsg, brErrMsg := ybService.CheckCommentPermission(sysUser.AdminId)
	if brMsg != "" {
		br.Msg = brMsg
		br.ErrMsg = brErrMsg
		return
	}
	//根据搜索条件查询留言列表
	var (
		err             error
		reportId        int
		reportChapterId int
	)
	reqReportId := this.GetString("ReportId", "")
	if reqReportId == "" {
		br.Msg = "请输入报告ID"
		br.ErrMsg = "请输入报告ID"
		return
	}
	reportId, err = strconv.Atoi(reqReportId)
	if err != nil {
		br.Msg = "请输入正确的报告ID"
		br.ErrMsg = "请输入正确的报告ID：" + err.Error()
		return
	}
	reqReportChapterId := this.GetString("ReportChapterId", "")
	if reqReportId == "" {
		br.Msg = "请输入报告ID"
		br.ErrMsg = "请输入报告ID"
		return
	}
	if reqReportChapterId != "" {
		reportChapterId, err = strconv.Atoi(reqReportChapterId)
		if err != nil {
			br.Msg = "请输入正确的章节ID"
			br.ErrMsg = "请输入正确的章节ID：" + err.Error()
			return
		}
	}

	likeList, err := yb.GetLikeListByReportId(reportId, reportChapterId, startSize, pageSize)
	if err != nil {
		br.Msg = "获取点赞列表失败！"
		br.ErrMsg = "获取点赞列表失败，Err:" + err.Error()
		return
	}
	var userIds string
	for _, v := range likeList {
		userIds += "," + strconv.Itoa(int(v.UserId))
	}
	// 查询点赞相关的用户
	var userOthers []*models.WxUser
	if len(userIds) > 0 {
		userOthers, err = models.GetWxUserListByUserIds(strings.Trim(userIds, ","))
		if err != nil {
			br.Msg = "查询点赞用户出错"
			br.ErrMsg = "查询点赞用户出错，Err:" + err.Error()
			return
		}
	}
	usersMap := make(map[uint64]*models.WxUser)
	companyIdArr := make([]int, 0)
	for _, v := range userOthers {
		usersMap[uint64(v.UserId)] = v
		companyIdArr = append(companyIdArr, v.CompanyId)
	}
	// 客户名称、状态
	companyIdNameMap := make(map[int]string, 0)
	companyIdStatusMap := make(map[int]string, 0)
	if len(companyIdArr) > 0 {
		companies, e := company.GetCompanyProductsByCompanyIdsAndProductId(companyIdArr, 1)
		if e != nil {
			br.Msg = "获取点赞客户信息失败"
			br.ErrMsg = "查询客户信息出错，Err:" + e.Error()
			return
		}
		companyLen := len(companies)
		for i := 0; i < companyLen; i++ {
			companyIdNameMap[companies[i].CompanyId] = companies[i].CompanyName
			companyIdStatusMap[companies[i].CompanyId] = companies[i].Status
		}
	}

	var list []*ybResp.LikeListItem
	for _, v := range likeList {
		tmp := new(ybResp.LikeListItem)
		tmp.LikeId = v.LikeId
		tmp.UserId = v.UserId
		if info, ok := usersMap[v.UserId]; ok {
			tmp.NickName = info.NickName
			tmp.RealName = info.RealName
			tmp.CompanyName = companyIdNameMap[info.CompanyId]
			tmp.CompanyStatus = companyIdStatusMap[info.CompanyId]
		}
		tmp.SourceAgent = v.SourceAgent
		tmp.ModifyTime = v.ModifyTime.Format(utils.FormatDateTime)
		list = append(list, tmp)
	}

	// 获取列表分页总数
	total, err := yb.GetLikeListTotalByReportId(reportId, reportChapterId)
	if err != nil {
		br.Msg = "获取点赞列表总数失败！"
		br.ErrMsg = "获取点赞列表总数失败，Err:" + err.Error()
		return
	}

	page := paging.GetPaging(currentIndex, pageSize, int(total))
	resp := ybResp.LikeListResp{
		List:   list,
		Paging: page,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
	return
}
