package yb

import (
	"errors"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/system"
	ybModels "hongze/hz_crm_api/models/yb"
	"hongze/hz_crm_api/models/yb/request"
	ybResp "hongze/hz_crm_api/models/yb/response"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

// 查询当前操作用户是否留言板管理员权限
func CheckCommentPermission(adminId int) (brMsg, brErrMsg string) {
	// 查询留言管理员的角色ID
	roleInfo, err := system.GetSysRoleByRoleTypeCode("yb_comment_admin")
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			brMsg = "该角色不存在!"
			brErrMsg = "该角色不存在,Err:" + err.Error()
			return
		} else {
			brMsg = "查询角色信息失败!"
			brErrMsg = "查询角色信息失败,Err:" + err.Error()
			return
		}
	}
	_, err = system.GetRoleIdsByAdminIdRoleId(adminId, roleInfo.RoleId)
	if err != nil {
		brMsg = "无权操作"
		brErrMsg = "无权操作,Err:" + err.Error()
		return
	}
	return
}

// GetProductComments 获取板块里的列表
func GetProductComments(adminId int, productType, keyWord, createDate string, startSize, pageSize int) (list []*ybResp.ProductCommentItemResp, total int64, err error, errMsg string) {
	condition := ""
	pars := make([]interface{}, 0)
	if productType != "" {
		condition += ` AND t.product_type = ? `
		pars = append(pars, productType)
	}

	if keyWord != "" {
		likeKey := `%` + keyWord + `%`
		condition += ` AND t.content like ? `
		pars = append(pars, likeKey)
	}
	if createDate != "" {
		createTime, _ := time.Parse(utils.FormatDate, createDate)
		nextTime := createTime.AddDate(0, 0, 1)
		condition += " and t.create_time >= ? and t.create_time < ?"
		pars = append(pars, createTime, nextTime)
	}

	// 获取数据列表
	var tmpList []*ybModels.ProductCommentItem
	tmpList, total, err = ybModels.GetProductCommentList(condition, pars, startSize, pageSize)
	if err != nil {
		errMsg = "获取评论列表失败,Err:" + err.Error()
		err = errors.New("获取评论列表失败!")
		return
	}
	var reportCommentIds string
	var reportIds string
	var userIds string
	questionIds := make([]int, 0)
	videoIds := make([]int, 0)
	roadVideoIds := make([]int, 0)
	for _, v := range tmpList {
		if v.ProductType == 1 {
			// 报告
			reportCommentIds += "," + strconv.Itoa(v.CommentId)
			if v.ReportId > 0 {
				reportIds += "," + strconv.Itoa(v.ReportId)
			}
		} else if v.ProductType == 2 {
			// 问答社区
			if v.CommunityQuestionId > 0 {
				questionIds = append(questionIds, v.CommunityQuestionId)
			}
		} else if v.ProductType == 3 {
			// 视频社区
			if v.CommunityQuestionId > 0 {
				videoIds = append(videoIds, v.CommunityQuestionId)
			}
		} else if v.ProductType == 4 {
			// 路演视频
			if v.CommunityQuestionId > 0 {
				roadVideoIds = append(roadVideoIds, v.CommunityQuestionId)
			}
		}
		userIds += "," + strconv.Itoa(v.UserId)
	}
	// 查询所有的回复列表
	replyListMap := make(map[int][]*ybResp.ReplyItem)
	if reportCommentIds != "" {
		reportCommentIds = "(" + strings.Trim(reportCommentIds, ",") + ")"
		replyList, tErr := ybModels.GetReplyByReplyCommentIds(reportCommentIds)
		if tErr != nil {
			errMsg = "获取回复列表失败,Err:" + tErr.Error()
			err = errors.New("获取回复列表失败")
			return
		}
		for _, v := range replyList {
			t := new(ybResp.ReplyItem)
			t.CommentId = v.CommentId
			t.Content = v.Content
			t.AdminId = v.AdminId
			t.CreateTime = v.CreateTime.Format(utils.FormatDateTime)
			t.AdminName = "admin"
			t.AdminImgUrl = utils.DEFAULT_HONGZE_SYS_LOGO
			t.ReplyCommentId = v.ReplyCommentId
			replyListMap[int(v.ReplyCommentId)] = append(replyListMap[int(v.ReplyCommentId)], t)
		}
	}
	// 查询报告标题,带日期
	reportMap := make(map[int]*models.ReportDetail)
	if reportIds != "" {
		reportIds = "(" + strings.Trim(reportIds, ",") + ")"
		reportList, tErr := models.GetReportByIds(reportIds)
		if tErr != nil {
			errMsg = "获取报告列表失败,Err:" + tErr.Error()
			err = errors.New("获取报告列表失败")
			return
		}
		for _, v := range reportList {
			reportMap[v.Id] = v
		}
	}

	// 查询问答内容
	questionMap := make(map[int]*ybModels.CommunityQuestion)
	if len(questionIds) > 0 {
		questionList, tErr := ybModels.GetQuestionByIds(questionIds)
		if tErr != nil {
			errMsg = "获取问答列表失败,Err:" + tErr.Error()
			err = errors.New("获取问答列表失败")
			return
		}
		for _, v := range questionList {
			questionMap[v.CommunityQuestionId] = v
		}
	}

	// 查询视频内容
	videoMap := make(map[int]*ybModels.CommunityVideo)
	if len(videoIds) > 0 {
		vdList, e := ybModels.GetCommunityVideoListByIds(videoIds)
		if e != nil {
			errMsg = "获取视频列表失败, Err:" + e.Error()
			err = errors.New("获取视频列表失败")
			return
		}
		for _, v := range vdList {
			videoMap[v.CommunityVideoId] = v
		}
	}

	// 查询路演视频内容
	roadVideoMap := make(map[int]*ybModels.RoadVideo)
	if len(roadVideoIds) > 0 {
		rvList, e := ybModels.GetRoadVideoListByIds(roadVideoIds)
		if e != nil {
			errMsg = "获取路演视频列表失败, Err:" + e.Error()
			err = errors.New("获取路演视频列表失败")
			return
		}
		for _, v := range rvList {
			roadVideoMap[v.RoadVideoId] = v
		}
	}

	// 查询联系人相关信息
	var userOthers []*models.WxUser
	if len(userIds) > 0 {
		userOthers, err = models.GetWxUserListByUserIds(strings.Trim(userIds, ","))
		if err != nil {
			errMsg = "查询用户出错,Err:" + err.Error()
			err = errors.New("查询用户出错")
			return
		}
	}
	//查询客户相关信息
	usersMap := make(map[int]*models.WxUser)
	companyIdMap := make(map[int]int)
	companyIdList := make([]int, 0)
	for _, v := range userOthers {
		usersMap[int(v.UserId)] = v
		if _, ok := companyIdMap[v.CompanyId]; !ok { //避免company_id重复append
			companyIdList = append(companyIdList, v.CompanyId)
			companyIdMap[v.CompanyId] = v.CompanyId
		}
	}

	// 查询相关用户的公司
	companyProductMap := make(map[int]*company.CompanyProduct)
	{
		if len(companyIdList) > 0 {
			var companyProductOthers []*company.CompanyProduct
			companyProductOthers, err = company.GetCompanyProductsByCompanyIdsAndProductId(companyIdList, 1)
			if err != nil {
				errMsg = "查询客户出错,Err:" + err.Error()
				err = errors.New("查询客户出错")
				return
			}
			for _, v := range companyProductOthers {
				companyProductMap[v.CompanyId] = v
			}
		}
	}

	// 将留言评论全部设置成已读
	err = ybModels.UpdateCommentSysIsRead(adminId)
	if err != nil {
		errMsg = "更新已读出错,Err:" + err.Error()
		err = errors.New("更新已读出错")
		return
	}
	list = make([]*ybResp.ProductCommentItemResp, 0)
	for _, v := range tmpList {
		tmp := new(ybResp.ProductCommentItemResp)
		tmp.UserId = v.UserId
		tmp.ReportId = v.ReportId
		tmp.ReportChapterId = v.ReportChapterId
		tmp.CommunityQuestionId = v.CommunityQuestionId
		tmp.CreateTime = v.CreateTime.Format(utils.FormatDateTime)
		if v.ProductType == 1 {
			tmp.ProductName = "研报"
			if v.ReportId > 0 {
				if rep, ok := reportMap[v.ReportId]; ok {
					if rep.VideoName == "" {
						tt, _ := time.ParseInLocation(utils.FormatDateTime, rep.PublishTime, time.Local)
						ttStr := tt.Format(utils.FormatMonthDayUnSpace)
						tmp.Title = rep.Title + `(` + ttStr + `)`
					} else {
						tmp.Title = rep.VideoName
					}
				}
			}
		} else if v.ProductType == 2 {
			tmp.ProductName = "问答社区"
			if que, ok := questionMap[v.CommunityQuestionId]; ok {
				tmp.Title = que.QuestionContent
			}
		} else if v.ProductType == 3 {
			tmp.ProductName = "视频社区"
			if vd, ok := videoMap[v.CommunityQuestionId]; ok {
				tmp.Title = vd.Title
			}
		} else if v.ProductType == 4 {
			tmp.ProductName = "线上路演"
			if rv, ok := roadVideoMap[v.CommunityQuestionId]; ok {
				tmp.Title = rv.Title
			}
		}
		tmp.Content = v.Content
		tmp.ProductType = v.ProductType
		tmp.RealName = v.RealName
		tmp.CommentId = v.CommentId
		tmp.IsTop = v.IsTop
		if existList, ok := replyListMap[v.CommentId]; ok && v.ProductType == 1 {
			tmp.ReplyList = existList
		}
		if info, ok := usersMap[v.UserId]; ok {
			tmp.RealName = info.RealName
			//客户信息
			if companyProductInfo, ok1 := companyProductMap[info.CompanyId]; ok1 {
				tmp.CompanyId = companyProductInfo.CompanyId
				tmp.CompanyName = companyProductInfo.CompanyName
				tmp.CompanyStatus = companyProductInfo.Status
				tmp.SellerName = companyProductInfo.SellerName
			}
		}
		list = append(list, tmp)
	}
	return
}

// DelProductComments 删除板块合辑里的留言
func DelProductComments(req request.CommentProductDelReq) (err error, errMsg string) {
	//查询评论状态,
	if req.ProductType == 1 {
		commentInfo, tErr := ybModels.GetCommentByCommentId(req.CommentId)
		if tErr != nil {
			if tErr.Error() == utils.ErrNoRow() {
				errMsg = "留言不存在或者已删除"
				err = errors.New("留言不存在或者已删除")
				return
			}
			errMsg = "查询留言失败!,Err:" + tErr.Error()
			err = errors.New("查询留言失败!")
			return
		}
		if commentInfo.Type == 1 { //删除留言
			err = ybModels.DeleteComment(req.CommentId)
			if err != nil {
				errMsg = "删除留言操作失败!,Err:" + err.Error()
				err = errors.New("删除留言操作失败!")
				return
			}
		} else { // 删除回复
			err = ybModels.DeleteCommentReply(req.CommentId)
			if err != nil {
				errMsg = "删除回复操作失败!,Err:" + err.Error()
				err = errors.New("删除回复操作失败!")
				return
			}
		}
	} else { //删除问答社区/视频社区/线上路演评论
		err, errMsg = DeleteQuestionComment(req.CommentId)
		return
	}
	return
}