
/*=============================================================================================
	author:ZhaoJun
	version:1.2
	email:2732810281@qq.com
=============================================================================================*/


//严格模式
/*-------------------------------------------------------------------------------------------*/	
'use strict';
const query=require('querystring')
/*-------------------------------------------------------------------------------------------*/
// qq的操作
/*-------------------------------------------------------------------------------------------*/	
class qq
{
	static geturl()
	{
		return 'https://graph.qq.com'
	}

	//code超时10分钟
	static code(co='code',state='',appid=$ToolTparty.qq.appid)
	{ 
		return `${qq.geturl()}/oauth2.0/authorize?response_type=${co}&client_id=${appid}&state=${state}&redirect_uri=${$ToolTparty.qq.redirect_uri}`
	}

	//超时时间3天
	static async accessToken(co,type='authorization_code')
	{
		if(!co)return false
		let data= await $Sys.model
        (
            '/request/fetch','get',
            [
				qq.geturl()+'/oauth2.0/token',
                {
					grant_type:type,
					client_id:$ToolTparty.qq.appid,
					client_secret:$ToolTparty.qq.appkey,
					code:co,
					redirect_uri:$ToolTparty.qq.redirect_uri
				}
            ]
		);

		try 
		{
			return query.parse(data.data)
		} 
		catch (error) 
		{
			console.error(err)
			return false	
		}
	}


	static async openid(obj)
	{
		if(!obj || !obj.access_token)return false
		let access=obj.access_token
		let data= await $Sys.model
        (
            '/request/fetch','get',
            [
				qq.geturl()+'/oauth2.0/me',
                {
					access_token:access
				}
            ]
		);

		if(data.data)data.data=data.data.replace(/callback\((.*)\);/,'$1')
		try 
		{
			return JSON.parse(data.data)
		} 
		catch (error) 
		{
			console.error(err)
			return false
		}
	}

	static async info(obj)
	{
		if(!obj || !obj.access_token || !obj.openid)return false
		let access=obj.access_token
		let openid=obj.openid
		let data= await $Sys.model
        (
            '/request/fetch','get',
            [
				qq.geturl()+'/user/get_user_info',
                {
					access_token:access,
					oauth_consumer_key:$ToolTparty.qq.appid,
					openid:openid
				}
            ]
		);

		return data.data
	}

	static async getOpenid(code)
	{
		let dataToken=await qq.accessToken(code)
		return await qq.openid(dataToken)
	}

	static async getInfo(code)
	{
		let dataToken=await qq.accessToken(code)
		let dataOPen=await qq.openid(dataToken)
		return await qq.info({...dataOPen,...dataToken})
	}
}
/*-------------------------------------------------------------------------------------------*/    
module.exports=qq;