const axios = require("axios");
const settings = require("../../../config/settings");
const system = require("../../system");
const centerChannelUrl = settings.centerChannelUrl();
const qifutongUrl = settings.qifutongUrl();

/**
 * 请求启服通的基类
 * 封装 获取 userpin token 
 * 统一请求方法
 * 统一日志记录
 */
class BaseClient {
    constructor(appKey, secret, url) {
        this.appKey = appKey;
        this.secret = secret;
        this.url = url
    }
    /**
     * 推送到 启服通
     * @param {*}  user 
     * @param {*} data 
     */
    async pushQiFuTong(user, data) {
        const header = await this.getLoginByUserName(user);
        return await this.postRequest(`${qifutongUrl}${this.url}`, data, header);
    }

    async getLoginByUserName(user = 'icp-deliver') {
        const token = await this.getAppTokenByAppKey(this.appKey, this.secret);
        const data = await this.postRequest(`${centerChannelUrl}/api/opreceive/accessAuth/springBoard`, {
            "actionType": "getLoginByUserName",
            "actionBody": {
                "channelUserId": user,
                "user": user,
                "userName": user
            }
        }, {
            token
        });
        return {
            token,
            userpin: data.userpin
        }
    }

    async getAppTokenByAppKey(appKey, secret) {
        const data = await this.postRequest(`${centerChannelUrl}/api/opreceive/accessAuth/getAppTokenByAppKey`, {
            "actionType": "getAppTokenByAppKey",
            "actionBody": {
                "appkey": appKey,
                "secret": secret
            }
        });
        return data.token
    }

    async postRequest(url, data, headers = {}) {
        try {
            console.log(` ${url} : 请求信息 ------- `);
            console.log(JSON.stringify(data))
            console.log(JSON.stringify(headers))
            let result = await axios.post(`${url}`, data, {
                headers: {
                    'Content-Type': 'application/json',
                    ...headers
                }
            });
            result = result.data;
            console.log(` ${url} : 返回信息 ------- `);
            console.log(result);
            system.execLogs(
                `请求启服通`, {
                url,
                data,
                headers
            },
                '交付请求',
                result,
                null
            ).catch(err => {
                console.log(`日志写入错误 ${url}`)
            });
            if (result.status === 0) {
                return result.data
            } else {
                throw new Error(result.msg)
            }
        } catch (err) {
            console.log(` ${url} : 返回错误信息 ------- `);
            console.log(err)
            throw (err)
        }
    }
}
module.exports = BaseClient;