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

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

    const corpid = SYSTEM_CONFIG.find(item => item.name === 'dingtalk_corpid').value;
    const appkey = SYSTEM_CONFIG.find(item => item.name === 'dingtalk_appkey').value;
    const appid = SYSTEM_CONFIG.find(item => item.name === 'dingtalk_clientId').value;
    const appsecret = SYSTEM_CONFIG.find(item => item.name === 'dingtalk_appsecret').value;

    const req = {
        url: `https://api.dingtalk.com/v1.0/oauth2/accessToken`,
        method: 'POST',
        content_type: 'application/json',
        data: JSON.stringify({
            appKey: appkey,
            appSecret: appsecret
        })
    }


    // console.log(request.toCURL(req))
    const res = request.parse(req).body.toObject()
    //     {
    //   "accessToken" : "fw8ef8we8f76e6f7s8dxxxx",
    //   "expireIn" : 7200
    // }

    if (res.accessToken) {
        SQL.push('system_sql', 'UPDATE sys_configs SET value =? WHERE name =?;', res.accessToken, 'dingtalk_access_token')
        console.mod('Event').fn('Apps').proc('dingtalk').info(`[getAccessToken] - ${res.accessToken}`)
        cache.set('oauth', 'dingtalk_access_token', res.accessToken, 7000 * 1000)
        return
    }
    console.mod('Event').fn('Apps').proc('dingtalk').error(`[getAccessToken] - ${JSON.stringify(res)}`)
    return
}