//go:build linux && cgo && msgaudit
// +build linux,cgo,msgaudit

package wework

import (
	"errors"
	"fmt"
	"github.com/silenceper/wechat/v2/work/msgaudit"
	"hongze/hongze_open_api/utils"
)

func (w *WeWorkMsgAuditClient) GetMsgAuditContent(seq, limit uint64, timeout int) (list []msgaudit.TextMessage, seqRes uint64, errMsg error) {
	client := w.Client
	//同步消息
	chatDataList, err := client.GetChatData(seq, limit, "", "", timeout)
	if err != nil {
		utils.FileLog.Info(fmt.Sprintf("企业微信 会议存档消息同步失败：%v \n\n", err))
		errMsg = errors.New("企业微信 会议存档消息同步失败："+err.Error())
		return
	}
	if len(chatDataList) == 0 {
		return
	}
	for _, chatData := range chatDataList {
		seqRes = chatData.Seq
		//消息解密
		chatInfo, err := client.DecryptData(chatData.EncryptRandomKey, chatData.EncryptChatMsg)
		if err != nil {
			utils.FileLog.Info(fmt.Sprintf("消息解密失败：%v \n", err))
			errMsg = errors.New("企业微信 消息解密失败："+err.Error())
			return
		}
		if chatInfo.Type == "image" {
			/*image, _ := chatInfo.GetImageMessage()
			sdkFileID := image.Image.SdkFileID

			isFinish := false
			buffer := bytes.Buffer{}
			indexBuf := ""
			for !isFinish {
				//获取媒体数据
				mediaData, err := client.GetMediaData(indexBuf, sdkFileID, "", "", 5)
				if err != nil {
					utils.FileLog.Info(fmt.Sprintf("媒体数据拉取失败：%v \n", err))
					errMsg = errors.New("企业微信 媒体数据拉取失败："+err.Error())
					return
				}
				buffer.Write(mediaData.Data)
				if mediaData.IsFinish {
					isFinish = mediaData.IsFinish
				}
				indexBuf = mediaData.OutIndexBuf
			}
			filePath, _ := os.Getwd()
			filePath = path.Join(filePath, "test.png")
			err := ioutil.WriteFile(filePath, buffer.Bytes(), 0666)
			if err != nil {
				utils.FileLog.Info(fmt.Sprintf("文件存储失败：%v \n", err))
				errMsg = errors.New("企业微信 文件存储失败："+err.Error())
				return
			}
			break*/
			continue
		}else if chatInfo.Type == "text" {
			msg, err := chatInfo.GetTextMessage()
			if err != nil {
				utils.FileLog.Info(fmt.Sprintf("查询消息类型失败：%v \n", err))
				errMsg = errors.New("企业微信 查询消息类型失败："+err.Error())
				return
			}
			utils.FileLog.Info(fmt.Sprintf("明文：%s \n", msg))
			list = append(list, msg)
		}
	}

	//释放SDK实例
	client.Free()
	return
}

