
/* eslint-disable */
import axios from 'axios';
import { getWxLoginUrl,getWxDomainUrl,getWxAPPID } from './index'

let wxLoginUrl = getWxLoginUrl();
let domain = getWxDomainUrl();
// let AAPID = getWxAPPID()
// console.log(AAPID)

// 查询url的参数
const getSearch =  (paraName) =>  {
  var url = document.location.toString();
  var arrObj = url.split("?");

  if (arrObj.length > 1) {
    var arrPara = arrObj[1].split("&");
    var arr;

    for (var i = 0; i < arrPara.length; i++) {
      arr = arrPara[i].split("=");

      if (arr != null && arr[0] == paraName) {
        return arr[1];
      }
    }
    return "";
  }
  else {
    return "";
  }
}


const _getUnionid = (openId) => {
	//alert('_getUnionid')
  return axios.get(`${wxLoginUrl}?openId=${openId}&type=15`)
}

const _getToken = (unionid) => {
 return axios.post(`${domain}/account/login/wechat`,{
    unionid
  })
} 

// 获取AppId
const _getAppId = (weixinCode) => {
 return axios.get(`${wxLoginUrl}/openid?code=${weixinCode}&type=15`)
}

//获取数据
export const getMessage = async (code, call) => {
  let appid,Unionid,token;
 
    appid = await _getAppId(code);
		//alert('appid:'+JSON.stringify(appid))
    if (appid.data.code == '000000') {
			//'oS3TnwCgn0w13GQzL0lvuHi-0ho4' 
			Unionid = await _getUnionid(appid.data.data.openId)
			//alert('Unionid:'+JSON.stringify(Unionid))
			console.log(Unionid.data.code)
			if(Unionid.data.code == '000000'){
				if(Unionid.data.data.unionid){
					window.sessionStorage.setItem("unionid", Unionid.data.data.unionid);
				}
				
				token = await _getToken(Unionid.data.data.unionid)
				call(token.data.data);
// 				if(token.data.code == '000000'){
// 					
// 					call(token.data.data);
// 				}
			}
		
    
  }
}

//弹出微信授权
export const wxGetCode = () => {
	let url = location.href
  let redirectUrl = encodeURIComponent(url);
  const appid = getWxAPPID();
  window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&#wechat_redirect`
}

//截取微信授权后的code
export const wxGetUrlCode = () => {
  // let weixinCode = '021SKjQz1nnukc0Y3rNz1WqbQz1SKjQy';
  let code = getSearch('code'); //获取返回路径的code
  return code || '';
}

// export const wxGetToken 
//判断当前是不是微信内部
export const is_weixin = () => {
  let ua = navigator.userAgent.toLowerCase();
　let isWeixin = ua.indexOf('micromessenger') != -1;
　if (isWeixin) {
  　　return true;
　}else{
  　　 return false;      
　}
}



