const crypto = require('crypto');

const axios = require('axios');

const moment = require('moment');

const urlEncode = require('urlencode');

const secret = 'SEC41c4e88eaa38ca8ccecd4ec12f32ca32e6c37a98d7cf4aca0103a68f4bf9d80d';
const accessToken = '20a30be34afef558f1d5e661a16ce5677a4b683344b5dc041f4f0a3131f3e035';

const config = require('../config/config.default.js').config;

/**
 * 向监控应用的钉钉群发送信息
 * 
 * [阿里云应用服务实时监控](https://arms.console.aliyun.com/) 有
 * 
 * [自定机器人接入](https://open.dingtalk.com/document/robots/customize-robot-security-settings)
 * 
*/
 class DingRobot {
    constructor(config) {
        this.atMobiles = config.atMobiles // 需要接收该消息的群人员
    }

    /**发送消息到群里*/
    send(content) {
        const nodeEnv = config.NODE_ENV;
        /**do not send error report to robot when in local env */
        if (nodeEnv === 'local') return;
        const timestamp = new Date().getTime();
        const stringToSign = `${timestamp}\n${secret}`;
        let hmac = crypto.createHmac('sha256', secret);
        let sign = hmac.update(stringToSign).digest('base64');
        sign = urlEncode(sign, 'utf-8');

        const msg = typeof content === 'object' ? JSON.stringify(content) : content;
        const url = `https://oapi.dingtalk.com/robot/send?access_token=${accessToken}&timestamp=${timestamp}&sign=${sign}`;
        const data = {
            msgtype: 'markdown',
            markdown: {
                title: '出错了',
                text: `### ${msg}\n > app:${__dirname}\n > env:${nodeEnv} \n\n > time:${moment().format()}`
            },
            at: {
                atMobiles: this.atMobiles,
            }
        };
        const atUsers = this.atMobiles.map(mobile => `\n #### @${mobile}`).join('');
        data.markdown.text += atUsers;
        axios.post(url, data);
    }
}

exports.DingRobot = DingRobot;







