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/types"
	"gitee.ltd/lxh/wechat-robot/internal/wechat"
	"gitee.ltd/lxh/xybot"
	"github.com/gofiber/fiber/v2/log"
)

// handlerMedia
// @description: 处理媒体消息
// @param msg *model.Message 消息记录
// @param client *xybot.Client 机器人客户端
func handlerMedia(msg *model.Message, client *xybot.Client) {
	var err error

	// 解析消息xml文件
	// 解析为结构体
	var media wechat.MediaMessage
	if err = xml.Unmarshal([]byte(msg.Content), &media); err != nil {
		log.Errorf("%v解析消息失败: %v", msg.Type, err.Error())
		return
	}

	var md5Str, bs64Str string
	switch msg.Type {
	case types.MsgTypeImage:
		fileUrl := ""
		md5Str = media.Img.Md5
		if media.Img.CdnBigImgUrl != "" {
			fileUrl = media.Img.CdnBigImgUrl
		} else if media.Img.CdnMidImgUrl != "" {
			fileUrl = media.Img.CdnMidImgUrl
		} else if media.Img.CdnThumbUrl != "" {
			fileUrl = media.Img.CdnThumbUrl
		} else {
			return
		}
		if bs64Str, err = client.Tool.CdnDownloadImg(media.Img.AesKey, fileUrl); err != nil {
			log.Errorf("图片文件下载失败: %s", err.Error())
			return
		}
	case types.MsgTypeVideo:
		if bs64Str, err = client.Tool.DownloadVideo(msg.ClientMsgId); err != nil {
			log.Errorf("视频文件下载失败: %s", err.Error())
			return
		}
	}

	// 下载完成，保存到OSS
	msg.FileUrl, err = minio.SaveBase64(bs64Str, md5Str)
	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
	}
}
