/**
 * Copyright (c) 2022 Yansen Zhang
 * wxcomponent is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
**/

package wxcomponent

import (
	"encoding/base64"
	"encoding/xml"

	"gitee.com/yansen_zh/wxcomponent/utils/encrypt"
	"gitee.com/yansen_zh/wxcomponent/utils/log"
)

// EncryptMessage 待解密数据
type EncryptMessage struct {
	XMLName    xml.Name `xml:"xml"`
	ToUserName string   `xml:"ToUserName"`
	Encrypt    string   `xml:"Encrypt"`
}

// DecodeMessage 解密消息
func DecodeMessage(src []byte) (*encrypt.XMLMap, error) {
	log.Info("解码 xml 数据: ", string(src))

	msg := EncryptMessage{}
	if err := xml.Unmarshal(src, &msg); err != nil {
		log.Error("解码 xml 数据失败: ", err.Error())
		return nil, err
	}

	bt1, e1 := base64.StdEncoding.DecodeString(msg.Encrypt)
	if e1 != nil {
		log.Error("解码 base 数据失败: ", e1.Error())
		log.Error("原始 base64 数据: ", msg.Encrypt)
		return nil, e1
	}

	bt2, e2 := encrypt.MsgDecode(bt1, aesKey)
	if e2 != nil {
		log.Error("解码加密数据失败: ", e2.Error())
		log.Error("待解密数据: ", string(bt1))
		return nil, e2
	}

	res := encrypt.XMLMap{}
	if err := xml.Unmarshal(bt2, &res); err != nil {
		log.Error("解码 xml 数据失败: ", err.Error())
		log.Info("待解码 xml 数据: ", string(bt2))
		return nil, err
	}

	return &res, nil
}