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

/**
 * 请求易代账
 * 封装 获取 userpin token 
 */

const pushYiDaZhang = async (data = {}) => {
    const ydzUrl = settings.ydzUrl();
    const { appKey, appSecret } = settings.ydzKey();
    // const openToken = getOpenTokenByAppKey(appKey, appSecret);
    const header = {
        "Content-Type": "application/json",
        "appKey": appKey,
        "appSecret": appSecret,
        "openToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NfdG9rZW4iOiI4MjE3MjExMS0xOGIzLTQ4YzgtYTUzMi01ZjVkZjE3ZmM0MTMiLCJzdWIiOiJpc3YiLCJhdWQiOiJpc3YiLCJuYmYiOjE2MDQ2NTcxNDEsImFwcElkIjoiMTA2NSIsInNjb3BlIjoiYXV0aF9hbGwiLCJpc3MiOiJjaGFuamV0IiwiZXhwIjoxNjA1MTc1NTQxLCJ1c2VySWQiOiI2MTAwMDQzMjU3NSIsImlhdCI6MTYwNDY1NzE0MSwib3JnSWQiOiI5MDAwMTIwNTYyNSIsIm9yZ0FjY291bnQiOiJ1MzEzbWN2czR5d2EifQ.j-97chbDAVZQ060EYaLqC6UldYdgdsA4FFrKmCT2tbo"
    }
    const manageId = await this.getManageIdByOpenToken(header);
    await this.postRequest(`${ydzUrl}/ydz/easyacctg/customer/create/{${manageId}}`, data, header);
}

const getOpenTokenByAppKey = async (appKey, appSecret) => {
    const data = await this.postRequest(`${ydzUrl}/api/opreceive/accessAuth/getAppTokenByAppKey`, {
        "Content-Type": "application/json",
        "appKey": appKey,
        "appSecret": appSecret
    });
    return data.token
}

const getManageIdByOpenToken = async (header) => {
    const data = await this.postRequest(`${centerChannelUrl}/ydz/setup/openAccess/MainTenant/findMainTenant`, {}, header);
    return { manageId: data.id }
}

const postRequest = async (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 = {
    pushYiDaZhang,
    getManageIdByOpenToken,
    // getAppTokenByAppKey,
    postRequest
}