// 引入crypto-js库（需要先安装：npm install crypto-js）
import CryptoJS from 'crypto-js';

class WXBizDataCrypt {
  constructor(appId, sessionKey) {
    this.appId = appId;
    this.sessionKey = sessionKey;
  }

  decryptData(encryptedData, iv) {
    try {
      // 解密
      const key = CryptoJS.enc.Base64.parse(this.sessionKey);
      const ivHex = CryptoJS.enc.Base64.parse(iv);
      const encryptedHex = CryptoJS.enc.Base64.parse(encryptedData);

      const decryptResult = CryptoJS.AES.decrypt(
        { ciphertext: encryptedHex },
        key,
        {
          iv: ivHex,
          mode: CryptoJS.mode.CBC,
          padding: CryptoJS.pad.Pkcs7
        }
      );

      // 将解密结果转换为JSON对象
      const decryptedStr = decryptResult.toString(CryptoJS.enc.Utf8);
      return JSON.parse(decryptedStr);
    } catch (err) {
      console.error('解密失败:', err);
      return {};
    }
  }
}

export default WXBizDataCrypt;