package comment

import (
	"errors"
	"fmt"
	"hongze/hongze_yb/global"
	reqComment "hongze/hongze_yb/models/request/comment"
	"hongze/hongze_yb/models/response"
	"hongze/hongze_yb/models/tables/wx_user"
	"hongze/hongze_yb/models/tables/yb_comment"
	"hongze/hongze_yb/services"
	"hongze/hongze_yb/services/user"
	"hongze/hongze_yb/services/wx_app"
	"hongze/hongze_yb/utils"
	"strconv"
	"time"
)

// Comment 发布留言
func Comment(user user.UserInfo, req reqComment.ReqComment, copyYb string) (ret response.RespCommentAdd, err error) {
	var errMsg string
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("Comment: userId=%d, err:%s， errMsg:%s", user.UserID, err.Error(), errMsg))
		}
	}()
	//校验请求入参
	if req.IsShowName != 0 && req.IsShowName != 1 {
		err = errors.New("匿名设置出错")
		return
	}
	if req.Content == "" {
		err = errors.New("请输入留言内容")
		return
	}
	reportId := req.ReportId
	reportChapterId := req.ReportChapterId

	if req.SourceAgent == 0 {
		err = errors.New("请输入留言来源")
		return
	}
	if req.ReportChapterId <=0 && req.ReportId <=0 && req.OldReportId <=0 && req.OldReportChapterId <=0{
		err = errors.New("请输入报告ID")
		return
	}
	if req.ReportId <=0 && req.OldReportId <= 0 {
		err = errors.New("请输入报告ID")
		return
	}
	// 敏感词过滤
	if user.RecordInfo.OpenID != "" && (user.RecordInfo.CreatePlatform == utils.USER_RECORD_PLATFORM_YB || user.RecordInfo.CreatePlatform == utils.USER_RECORD_PLATFORM_COPY_YB) {   //只有小程序的用户才能走敏感词过滤接口
		checkResult, tErr := wx_app.MsgSecCheck(user.RecordInfo.OpenID, req.Content, copyYb)
		/*if tErr != nil {
			errMsg = "敏感词过滤失败" + tErr.Error()
			err = errors.New("敏感词过滤失败")
			return
		}*/
		if tErr == nil {
			if checkResult.Result != nil {
				if checkResult.Result.Suggest != "pass" {
					errMsg = "含有违禁词，不允许发布：" + checkResult.Result.Suggest +".命中标签："+strconv.Itoa(checkResult.Result.Label)
					err = errors.New("含有违禁词，不允许发布。")
					return
				}
			}
		}
	}
	// 判断是否有留言权限
	err, errMsg = services.CheckSimpleCompanyProduct(user)
	if err != nil {
		return
	}
	//处理老报告, 转化成新报告ID
	if req.ReportChapterId <=0 && req.ReportId <=0 && (req.OldReportId >0 || req.OldReportChapterId > 0) {
		reportId, reportChapterId, err, errMsg = services.GetReportIdReportChapterIdByOldReportId(uint64(req.OldReportId), uint64(req.OldReportChapterId))
		if err != nil {
			return
		}
	} else {
		// 判断报告ID是否正确
		err, errMsg = services.CheckReportExistByReportIdReportChapterId(reportId, reportChapterId)
		if err != nil {
			return
		}
	}

	//新增留言
	now := time.Now()
	commentInfo := &yb_comment.YbComment{
		UserId:             user.UserID,
		RealName:           user.RealName,
		Content:            req.Content,
		ReportId:           reportId,
		ReportChapterId:    reportChapterId,
		IsShowName:         req.IsShowName,
		SourceAgent:        req.SourceAgent,
		Type:               1,
		Enabled:            1,
		CreateTime:         now,
		ModifyTime:         now,
		OldReportId:        req.OldReportId,
		OldReportChapterId: req.OldReportChapterId,
		IsHot: 1,
		HotTopTime: time.Now(),
	}
	err = commentInfo.Create()
	if err != nil {
		errMsg = err.Error()
		err = errors.New("新增留言出错")
		return
	}
	ret.CommentId = commentInfo.CommentId
	return
}

// Delete 删除留言
func Delete(user user.UserInfo, req *reqComment.ReqDel) (err error) {
	var errMsg string
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("comment Delete: userId=%d, err:%s， errMsg:%s", user.UserID, err.Error(), errMsg))
		}
	}()
	if req.CommentId <= 0 {
		err = errors.New("请输入留言ID")
		return
	}
	//校验请求入参
	commentInfo, err := yb_comment.GetSimpleByCommentId(req.CommentId)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("查询留言出错")
		return
	}
	if commentInfo.CommentId <= 0 {
		err = errors.New("留言不存在")
		return
	}
	if commentInfo.UserId != user.UserID {
		err = errors.New("不允许删除他人的留言")
		return
	}
	if commentInfo.Type != 1 {
		err = errors.New("不允许删除回复")
		return
	}

	err = yb_comment.Delete(user.UserID, commentInfo.CommentId)
	if err != nil {
		errMsg = err.Error()
		err = errors.New("删除留言出错")
		return
	}
	return
}

// MyList 我的留言列表
func MyList(user user.UserInfo,  reportId, reportChapterId, oldReportId, oldReportChapterId int) (ret response.RespMyCommentList, err error) {
	list, err := List(user, reportId, reportChapterId, oldReportId, oldReportChapterId, false, 0, 0)
	if err != nil {
		return
	}
	//查询我的最新一条留言是否勾选匿名的设置
	lastComment, tErr := yb_comment.GetMyLatestComment(user.UserID)
	if tErr == nil {
		ret.IsShowName = lastComment.IsShowName
	}
	ret.List = list.List
	return
}

// List 查询精选留言列表或我的留言列表
func List(user user.UserInfo,  reportId, reportChapterId, oldReportId, oldReportChapterId int, hotFlag bool, pageIndex, pageSize int) (ret response.RespCommentList, err error) {
	var errMsg string
	defer func() {
		if err != nil {
			global.LOG.Critical(fmt.Sprintf("comment List: userId=%d, err:%s， errMsg:%s", user.UserID, err.Error(), errMsg))
		}
	}()

	if reportId <=0 && reportChapterId <=0 && oldReportId <=0 && oldReportChapterId <=0{
		err = errors.New("请输入报告ID")
		return
	}
	if reportId <=0 && oldReportId <= 0 {
		err = errors.New("请输入报告ID")
		return
	}
	//处理老报告, 转化成新报告ID
	if  reportId <=0 && reportChapterId <=0 && (oldReportId >0 || oldReportChapterId > 0) {
		reportId, reportChapterId, err, errMsg = services.GetReportIdReportChapterIdByOldReportId(uint64(oldReportId), uint64(oldReportChapterId))
		if err != nil {
			return
		}
	} else {
		// 判断报告ID是否正确
		err, errMsg = services.CheckReportExistByReportIdReportChapterId(reportId, reportChapterId)
		if err != nil {
			return
		}
	}
	offset := (pageIndex -1)*pageSize
	var commentList []*yb_comment.YbComment
	var total int64
	//查询精选留言
	if hotFlag {
		if reportId > 0 {
			commentList, err = yb_comment.GetHotListByReportId(reportId, reportChapterId, offset, pageSize)
			if err != nil {
				errMsg = err.Error()
				err = errors.New("查询精选留言列表出错")
				return
			}
			total, err = yb_comment.GetHotListTotalByReportId(reportId, reportChapterId)
			if err != nil {
				errMsg = err.Error()
				err = errors.New("查询精选留言总数出错")
				return
			}
		}else {
			commentList, err = yb_comment.GetHotListByOldReportId(oldReportId, oldReportChapterId, offset, pageSize)
			if err != nil {
				errMsg = err.Error()
				err = errors.New("查询精选留言列表出错")
				return
			}
			total, err = yb_comment.GetHotListTotalByOldReportId(oldReportId, oldReportChapterId)
			if err != nil {
				errMsg = err.Error()
				err = errors.New("查询精选留言总数出错")
				return
			}
		}
	} else {
		//查询个人留言
		if reportId > 0{
			commentList, err = yb_comment.GetListByUserIdReportId(user.UserID, reportId, reportChapterId)
			if err != nil {
				errMsg = err.Error()
				err = errors.New("查询精选留言列表出错")
				return
			}
		}else {
			commentList, err = yb_comment.GetListByUserIdOldReportId(user.UserID, oldReportId, oldReportChapterId)
			if err != nil {
				errMsg = err.Error()
				err = errors.New("查询精选留言列表出错")
				return
			}
		}

	}

	var commentIds []uint64
	var userIds []uint64
	for _, v := range commentList {
		commentIds = append(commentIds, v.CommentId)
		userIds = append(userIds, v.UserId)
	}
	// 查询所有的回复列表
	replyListMap := make(map[uint64][]*response.ReplyItem)
	if len(commentIds) > 0 {
		replyList, tErr := yb_comment.GetReplyListByReplyCommentId(commentIds)
		if tErr != nil {
			errMsg = tErr.Error()
			err = errors.New("查询回复出错")
			return
		}
		for _, v := range replyList {
			t := new(response.ReplyItem)
			t.CommentId = v.CommentId
			t.Content = v.Content
			t.AdminId = v.AdminId
			t.CreateTime = v.CreateTime
			t.ReplyCommentId = v.ReplyCommentId
			t.AdminName = "弘则研究"
			t.AdminImgUrl = utils.DEFAULT_HONGZE_SYS_LOGO
			replyListMap[v.ReplyCommentId] = append(replyListMap[v.ReplyCommentId], t)
		}
	}

	// 查询精选留言相关的用户
	var userOthers []*wx_user.WxUser
	if len(userIds) > 0 {
		userOthers, err = wx_user.GetByUserIds(userIds)
		if err != nil {
			errMsg = err.Error()
			err = errors.New("查询精选留言用户出错")
			return
		}
	}
	usersMap := make(map[uint64]*wx_user.WxUser)
	for _, v := range userOthers {
		usersMap[v.UserID] = v
	}
	var list []*response.RespCommentItem
	for _, v := range commentList {
		tmp := new(response.RespCommentItem)
		tmp.CommentId = v.CommentId
		tmp.UserId = v.UserId
		tmp.UserName = "匿名用户"+strconv.Itoa(int(3333+v.UserId))
		tmp.UserImgUrl = utils.DEFAULT_HONGZE_USER_LOGO
		if info, ok := usersMap[v.UserId]; ok && v.IsShowName == 1{
			tmp.UserName = info.NickName
			tmp.UserImgUrl = info.Headimgurl
		}
		tmp.Content = v.Content
		tmp.IsHot = v.IsHot
		tmp.IsTop = v.IsTop
		tmp.HotTopTime = v.HotTopTime
		tmp.CreateTime = v.CreateTime
		tmp.IsShowName = v.IsShowName
		if existList, ok := replyListMap[v.CommentId]; ok {
			tmp.ReplyList = existList
		}
		list = append(list, tmp)
	}
	ret.List = list
	if hotFlag {
		ret.Paging = response.GetPaging(pageIndex, pageSize, int(total))
	}
	return
}
