const SQL = require('sql')
const cache = require('cache');
const request = require('request');

function main() {
    const SYSTEM_CONFIG = SQL.cache.query(
        "system_sql",
        86400, // 缓存时间，单位秒，0表示不缓存，-1表示永久缓存，默认缓存时间为1天
        "SELECT * FROM `sys_configs` WHERE `delete_time` IS NULL;",
    );

    const appid = SYSTEM_CONFIG.find(item => item.name === 'wechat_appid').value;
    const secret = SYSTEM_CONFIG.find(item => item.name === 'wechat_appsecret').value;

    // GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
    // {"access_token":"ACCESS_TOKEN","expires_in":7200}

    const req = {
        url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`
    }

    // console.log(request.toCURL(req))
    const res = request.parse(req).body.toObject()
    if (res.access_token) {
        SQL.push('system_sql', 'UPDATE sys_configs SET value =? WHERE name =?;', res.access_token, 'wechat_access_token')
        console.mod('Event').fn('apps').proc('wechat').info(`[getAccessToken] - ${res.access_token}`)
        cache.set('oauth', 'wechat_access_token', res.access_token, 7000 * 1000)
        return
    }
    console.mod('Event').fn('apps').proc('wechat').error(`[getAccessToken] - ${JSON.stringify(res)}`)
    return
}


// const accessToken = cache.get('oauth', 'wechat')
// if (accessToken == null) {
//     return false
// }