const axios = require("axios");
const settings = require("../../config/settings");
const system = require("../system");
const ydzUrl = settings.ydzUrl();
const redisClient = system.getObject("util.redisClient");
const ydz_prefix = "ydz:";
/**
 * 请求易代账
 * 封装 获取 userpin token 
 */

const pushYiDaZhang = async (data = {}) => {
    const { appKey, appSecret } = settings.ydzKey();
    const openToken = JSON.parse(await redisClient.get(`${ydz_prefix}ydzToken`)).access_token;
    console.log('----------------------------open-----------------------');
    console.log(openToken);
    const header = {
        "Content-Type": "application/json",
        "appKey": appKey,
        "appSecret": appSecret,
        "openToken": openToken
    }
    const manageId = await getManageIdByOpenToken(header);
    const pushYDZResult = await postRequest(`${ydzUrl}/ydz/easyacctg/customer/create/${manageId}`, data, header);
    return pushYDZResult;
}

const getManageIdByOpenToken = async (headers) => {
    const url = `${ydzUrl}/ydz/setup/openAccess/MainTenant/findMainTenant`
    const rs = await getRequest(url, {}, headers);
    return rs.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: {
                ...headers
            }
        });
        result = result.data;
        console.log(` ${url} : 返回信息 ------- `);
        console.log(result);
        system.execLogs(
            `请求易代账`, {
            url,
            data,
            headers
        },
            '交付请求',
            result,
            null
        ).catch(err => {
            console.log(`日志写入错误 ${url}`)
        });
        if (result.assocTenantId) {
            return result
        } else {
            throw new Error(result.msg)
        }
    } catch (err) {
        console.log(` ${url} : 返回错误信息 ------- `);
        console.log(err);
        throw (err)
    }
}

const getRequest = async (url, data, headers = {}) => {
    try {
        console.log(` ${url} : 请求信息 ------- `);
        console.log(JSON.stringify(headers));
        const res = await axios.get(url, {
            params: data,
            headers: headers
        });
        return res.data;
    } catch (err) {
        console.log(` ${url} : 返回错误信息 ------- `);
        console.log(err);
        throw (err)
    }
}

module.exports = {
    pushYiDaZhang,
    getManageIdByOpenToken,
    postRequest,
    getRequest
}