package yb

import (
	"errors"
	"fmt"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/yb"
	"hongze/hz_crm_api/models/yb/response"
	"hongze/hz_crm_api/utils"
	"time"
)

// GetBulletChatList 获取弹幕列表
func GetBulletChatList(condition string, pars []interface{}, startSize, pageSize int) (total int, resp []*response.BulletChatItem, err error) {
	resp = make([]*response.BulletChatItem, 0)

	t, list, e := yb.GetBulletChatPageList(condition, pars, "", startSize, pageSize)
	if e != nil {
		err = errors.New("获取弹幕列表失败 Err:" + e.Error())
		return
	}
	if len(list) == 0 {
		return
	}
	total = t

	// 用户名称
	userIdArr := make([]int, 0)
	for i := range list {
		userIdArr = append(userIdArr, list[i].UserId)
	}
	userIds := utils.IntArr2joinString(userIdArr, ",")
	userMap := make(map[int]string, 0)
	if userIds != "" {
		userList, e := models.GetWxUserListByUserIds(userIds)
		if e != nil {
			err = errors.New("获取弹幕用户信息失败, Err: " + e.Error())
			return
		}
		for i := range userList {
			userMap[int(userList[i].UserId)] = userList[i].RealName
		}
	}

	for _, v := range list {
		sa := 1
		if v.SourceAgent == 2 || v.SourceAgent == 4 {
			sa = 2
		}
		item := &response.BulletChatItem{
			Id:          v.Id,
			Title:       v.Title,
			Content:     v.Content,
			Source:      v.Source,
			Seconds:     fmt.Sprint(v.Seconds),
			UserName:    userMap[v.UserId],
			SourceAgent: sa,
			CreateTime:  v.CreateTime.Format(utils.FormatDateTime),
		}
		resp = append(resp, item)
	}
	return
}

// SoftDeleteBulletChat 删除弹幕
func SoftDeleteBulletChat(adminId, id int) (err error) {
	item, e := yb.GetBulletChatById(id)
	if e != nil {
		err = errors.New("获取弹幕信息失败, Err:" + e.Error())
		return
	}
	if item.IsDeleted != 0 {
		err = errors.New("弹幕状态有误")
		return
	}

	nowTime := time.Now().Local()
	updateCols := []string{"ModifyTime", "OpAdminId", "IsDeleted", "DeleteTime"}
	item.ModifyTime = nowTime
	item.OpAdminId = adminId
	item.IsDeleted = 1
	item.DeleteTime = nowTime
	if e = item.Update(updateCols); e != nil {
		err = errors.New("删除弹幕失败, Err: " + e.Error())
		return
	}
	return
}
