import md5 from 'js-md5'
import qs from 'qs'
import { useSelector } from 'react-redux'

export default function Design() {
  /**
   * 构建签名
   * @param obj 参数对象，对象中的所有属性全部参与签名的生成
   * @returns {string} 签名
   */
  const buildSign = obj => {
    let signParameterArray = []
    for (let key in obj) {
      signParameterArray.push(`${key}=${obj[key]}`)
    }

    let signPlaintext = signParameterArray.sort().join('&')
    return md5(signPlaintext).toUpperCase()
  }

  /**
   * 构建2.0版本签名
   * @param appId 第三方企业id
   * @param expireTime 时间戳，取当前时间即可
   * @param userFlag 用户标记
   * @param appSecret 企业密钥
   * @returns {string} 签名
   */
  const buildVersion2Sign = (appId, expireTime, userFlag, appSecret) => {
    let signParameterObj = {
      app_id: appId,
      expire_time: expireTime,
      user_flag: userFlag,
      app_secret: appSecret
    }

    return buildSign(signParameterObj)
  }

  const { userInfo } = useSelector(state => state.user)
  const buildQueryString = () => {
    const appId = '54d9adec77d0402794018d166110f3dd'
    const appSecret = '08097010E0EF4B85EE2B8CE438328249'
    const userFlag = userInfo.id
    const expireTime = Date.now()
    const sign = buildVersion2Sign(appId, expireTime, userFlag, appSecret)
    let params = {
      app_id: appId,
      expire_time: expireTime,
      user_flag: userFlag,
      device_type: 1,
      kind_id: 438,
      version: '2.0',
      sign: sign,
      enable_authorize: '1',
      taxpayer_name: 'chuangkit',
      taxpayer_phone: '13820659475',
      taxpayer_number: '91120116636067462H',
      env: 'prod',
      reptile: 1
    }
    return qs.stringify(params)
  }

  const src = `https://www.chuangkit.com/apiauthorize?${buildQueryString()}`

  return <iframe src={src} style={{ border: 0, width: '100% ', height: '100%' }}></iframe>
}
