/**
 * encryptionFun()
  示例1 http://xxx.com?id=123
  encryptionFun('id=123')

  示例2 http://xxx.com   {"id":123}
  encryptionFun('{"id":123}')

  示例3 http://xxx.com?id=123&name=张三   {"id":123}
  encryptionFun('id=123&name=张三{"id":123}')
*/

import { generateUUID } from "@/utils/index" 
import { sha256 } from 'js-sha256'

/**
 * 
 * @param { str } raw 参数用&隔开
 * @param { Object } body
 * @returns 
*/
export const encryptionFun = ({raw, body, appId, AppSecret}) => {
  const initSign = {
    appId,
    nonce: generateUUID(),
    timestamp: new Date().getTime() + 3000,
  }
  const _initSign = Object.keys(initSign).reduce((str, key) => str += `&${key}=${initSign[key]}`, '')
  const paramsStr = _initSign.slice(1, _initSign.length) + AppSecret
  let str = ''
  if (raw) {
    str += decodeURIComponent(raw)
  }
  if (body && Object.keys(body).length) {
    str += decodeURIComponent(JSON.stringify(body))
  }
  // console.log('str:', str, 'paramsStr:', paramsStr)
  return {
    ...initSign,
    sign: sha256(str + paramsStr)
  }
}
