package yb

import (
	"errors"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/yb"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"time"
)

// SoftDeleteQuestionComment 删除问题评论
func SoftDeleteQuestionComment(questionCommentId int) (err error, errMsg string) {
	errMsg = `删除成功`
	questionCommentInfo, err := yb.GetQuestionCommentById(questionCommentId)
	if err != nil {
		errMsg = "查找评论失败"
		if err.Error() == utils.ErrNoRow() {
			errMsg = "该评论不存在"
		}
		return
	}

	//标记删除
	questionCommentInfo.Enabled = 0
	questionCommentInfo.ModifyTime = time.Now()
	err = questionCommentInfo.Update([]string{"Enabled", "ModifyTime"})
	if err != nil {
		errMsg = "删除提问失败"
		return
	}

	// 删除评论后的逻辑处理
	go afterDeleteComment(questionCommentInfo)
	return
}

// DeleteQuestionComment 删除问题评论
func DeleteQuestionComment(questionCommentId int) (err error, errMsg string) {
	errMsg = `删除成功`
	questionCommentInfo, err := yb.GetQuestionCommentById(questionCommentId)
	if err != nil {
		errMsg = "查找评论失败"
		if err.Error() == utils.ErrNoRow() {
			errMsg = "该评论不存在"
		}
		return
	}

	//标记删除
	questionCommentInfo.Enabled = 0
	questionCommentInfo.ModifyTime = time.Now()
	err = questionCommentInfo.Delete()
	if err != nil {
		errMsg = "删除提问失败"
		return
	}

	// 删除评论后的逻辑处理
	go afterDeleteComment(questionCommentInfo)
	return
}

// SetHotQuestionComment 设置/取消 问题评论精选
func SetHotQuestionComment(questionCommentId int) (err error, errMsg string) {
	errMsg = `操作失败`
	questionCommentInfo, err := yb.GetQuestionCommentById(questionCommentId)
	if err != nil {
		errMsg = "查找评论失败"
		if err.Error() == utils.ErrNoRow() {
			errMsg = "该评论不存在"
		}
		return
	}

	//var isHot int8
	isHot := int8(1)
	if questionCommentInfo.IsHot == 1 {
		isHot = 0
	}
	//标记删除
	questionCommentInfo.IsHot = isHot //是否设置精选（0-未设置，1-已设置）
	questionCommentInfo.HotTopTime = time.Now()
	questionCommentInfo.HotTime = time.Now()
	questionCommentInfo.ModifyTime = time.Now()
	err = questionCommentInfo.Update([]string{"IsHot", "HotTopTime", "HotTime", "ModifyTime"})
	if err != nil {
		errMsg = "操作失败"
	}
	return
}

// afterDeleteComment 删除评论后的逻辑处理
func afterDeleteComment(communityQuestionComment *yb.YbCommunityQuestionComment) {
	var err error
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("问答评论信息删除后，标记站内消息失败"+time.Now().Format(utils.FormatDateTime)+";Err:"+err.Error(), 3)
		}
	}()

	sourceType := 0
	switch communityQuestionComment.Source {
	case 1:
		sourceType = services.CompanyApprovalMessageSourceTypeByQuestionComment
	case 2:
		sourceType = services.CompanyApprovalMessageSourceTypeByVideoComment
	case 3:
		sourceType = services.CompanyApprovalMessageSourceTypeByRoadVideoComment
	default:
		err = errors.New("sourceType有误")
		return
	}
	err = company.CancelCompanyApprovalMessage(int(communityQuestionComment.CommunityQuestionCommentId), sourceType)
	return
}
