package message

import (
	"encoding/xml"
	"gitee.ltd/lxh/wechat-robot/internal/minio"
	"gitee.ltd/lxh/wechat-robot/internal/model"
	"gitee.ltd/lxh/wechat-robot/internal/utils"
	"gitee.ltd/lxh/wechat-robot/internal/wechat"
	"gitee.ltd/wechat-client/xybot"
	"github.com/gofiber/fiber/v2/log"
	"net/url"
	"slices"
)

// handlerEmoticon
// @description: 处理表情包
func handlerEmoticon(msg *model.Message, client *xybot.Client) {
	var err error

	var emoticon wechat.EmoticonMessage
	if err = xml.Unmarshal([]byte(msg.Content), &emoticon); err != nil {
		log.Errorf("%v解析消息失败: %v", msg.Type, err.Error())
		return
	}
	// 如果表情包是以域名开头，直接下载，否则不管
	u, _ := url.Parse(emoticon.Emoji.Cdnurl)
	// 判断是不是表情包域名
	emoticonHostArray := []string{"vweixinf.tc.qq.com", "wxapp.tc.qq.com"}
	if slices.Contains(emoticonHostArray, u.Host) {
		var bs []byte
		if bs, err = utils.DownloadFile(emoticon.Emoji.Cdnurl); err != nil {
			log.Errorf("下载表情包失败: %v", err.Error())
			return
		}
		// 下载完成，保存到OSS
		msg.FileUrl, err = minio.SaveBytes(bs, emoticon.Emoji.Md5)
		if err != nil {
			log.Errorf("表情包保存到Minio失败: %s", err.Error())
			return
		}
		// 更新数据库
		if err = model.GetDB().Model(&msg).Where("id = ?", msg.ID).Update("file_url", msg.FileUrl).Error; err != nil {
			log.Errorf("更新数据库失败: %s", err.Error())
			return
		}
	}
}
