import wechatService from '@/service/WechatService'
import jweixin from 'jweixin-module'
import stringRandom from 'string-random'
import JsSHA from 'jssha'
import Env from './Env'

const wechat = {
  oauth2: ({appid, redirectUri, responseType = 'code', scope = 'snsapi_base', state = 'WECHAT'} = {}) => {
    let oauth2URL = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' + redirectUri + '&response_type=' + responseType + '&scope=' + scope + '&state=' + state + '#wechat_redirect'
    window.location.href = oauth2URL
  },
  hashSHA1: (str) => {
    let hashObj = new JsSHA('SHA-1', 'TEXT', {numRounds: 1})
    hashObj.update(str)
    let shaStr = hashObj.getHash('HEX')
    return shaStr
  },
  async wxConfig () {
    let jssdkUser = wechatService.getWxJssdkUser()
    if (!jssdkUser.ticket) {
      let ticketResult = await wechatService.getTicket({appid: jssdkUser.appid})
      jssdkUser.ticket = ticketResult.ticket
    }
    let timestamp = parseInt(new Date().getTime().toString().substr(0, 10))
    let nonceStr = stringRandom(32)
    let url = window.location.href
    let signatureStr = 'jsapi_ticket=' + jssdkUser.ticket + '&noncestr=' + nonceStr + '&timestamp=' + timestamp + '&url=' + url
    let signature = this.hashSHA1(signatureStr)
    jweixin.ready(res => {
       wechatService.setWxConfigInitStatus(true)
       //console.warn('#### wx.ready ####', res)
       //alert('wx.ready: ' + JSON.stringify(res))
    })
    jweixin.error(res => {
       //console.warn('#### wx.error ####', res)
       //alert('wx.error: ' + JSON.stringify(res))
    })
    let configData = {
       //debug: false, 					// 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
       appId: jssdkUser.appid, 			// 必填，公众号的唯一标识
       timestamp, 						// 必填，生成签名的时间戳
       nonceStr, 						// 必填，生成签名的随机串
       signature, 						// 必填，签名
       jsApiList: [] 					// 必填，需要使用的JS接口列表
     }
       console.log('signatureStr', signatureStr)
       console.log('configData', JSON.stringify(configData))
       jweixin.config(configData)
    }
}

export default wechat
