const axios = require("axios");
const settings = require("../../config/settings");
const system = require("../system");
const moment = require('moment');
const ftConfig = settings.ftConfig();
const _ = require("lodash")
const uuidv4 = require('uuid/v4');


/**
 * 发送 post 请求
 * @param {*} url 
 * @param {*} data 
 * @param {*} headers 
 */
const postRequest = async (url, data, headers = {}) => {
    try {
        console.log(`${url} : 请求数据 ------- `);
        console.log(JSON.stringify(data))
        let result = await axios.post(url, data, {
            headers: {
                'Content-Type': 'application/json',
                ...headers
            },
            timeout: 5000,
        });
        result = result.data;
        console.log(`${url} : 返回数据 ------- `);
        console.log(JSON.stringify(result));
        if (result.code == 1) {
            return result.data
        } else {
            throw new Error(result.errMsg);
        }
    } catch (err) {
        console.log("------ 财税中心err -----");
        console.log(err)
        throw (err)
    }
}

/**
 * 向财税 项目 发送消息 (不带签名)
 * @param {*} url 
 * @param {*} data 
 * @param {*} headers 
 */
const postToFt = (url, data, headers = {}) => {
    return postRequest(`${ftConfig.url}${url}`, data, headers = {})
}

/**
 * 租户 向财税 项目 发送消息 带签名
 * @param {*} url 
 * @param {*} data 
 * @param {*} headers 
 */
const postToFtBySign = async (url, data, headers = {}) => {
    let tenantInfo = await getChannelCompany(data.companyId);
    data.companyId = tenantInfo.id;
    let sign = system.signValid(data, tenantInfo.signSecret);
    var res = await postRequest(`${ftConfig.url}${url}`, { ...data, sign }, headers = {});
    console.log("postToFtBySign:res--------------------------------------" + JSON.stringify(res));
    return res;
}

/**
 * 财税  获取 租户信息
 */
const getChannelCompany = async (id) => {
    let reqData = {
        channelCode: ftConfig.channelCode,
    }
    let sign = system.signValid(reqData, ftConfig.secret);
    let companyData = await postToFt("/company/getChannelCompany", {
        ...reqData,
        sign
    });
    companyData = companyData.datas;
    if (id) {
        companyData = _.find(companyData, (item) => {
            return item.id === id
        })
        if (!companyData) {
            throw new Error("查不到租户信息");
        }
    }
    console.log("getChannelCompany:companyData------------------------------------------" + companyData);
    return companyData;
}

/**
 * 建账
 * @param {*} deliverData 
 * @param {*} pobj 
 */
const addCusAccApplyInfo = async (deliverData, pobj) => {
    const accountStandard = {
        "小企业会计准则": 1,
        "企业会计准则": 2
    }
    const valueAddedTax = {
        "smallScaleTaxpayer": 0,
        "generalTaxpayer": 1,
    }
    let reqData = {
        accountStandard: accountStandard[pobj.accountingType],
        applyDate: moment(pobj.time).format('YYYY-MM-DD'),
        contact: deliverData.delivery_info.contactsName,
        creditCode: deliverData.delivery_info.creditCode,
        customerName: deliverData.delivery_info.companyName,
        phoneNumber: deliverData.delivery_info.contactsPhone,
        valueAddedTax: valueAddedTax[pobj.taxpayerType],
        serviceTime: Math.ceil(moment(deliverData.delivery_info.serviceEndTime).diff(moment(deliverData.delivery_info.serviceStartTime), 'months', true)).toString(),
        initPeriod: parseInt(moment(deliverData.delivery_info.serviceStartTime).format('YYYYMMDD')),
        companyId: pobj.supplier
    }
    await postToFtBySign('/cusAccApplyInfo/addCusAccApplyInfo', reqData);
}

/**
 * 交付单 处理 向融易算 发消息
 * @param {*} data 
 */
const feedbackToRys = async (data) => {
    let reqData = {
        BizId: data.bizId
    };
    if (data.orderStaus === true) {
        reqData = {
            ...reqData,
            AuditResult: 1,
            ServiceStartTime: moment(data.setupAt).format('YYYY-MM-DD')
        }
    }
    if (data.orderStaus === false) {
        reqData = {
            ...reqData,
            AuditResult: 2,
            Note: data.note
        }
    }
    let resData = await system.queueOper({
        pushUrl: settings.rysUrl() + "/service/feedback",
        // pushUrl: settings.rysUrl() + "/web/bizchance/deliverybillCtl/testfeedback",
        actionType: "feedback",
        messageBody: reqData,
        headData: {
            'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTg0MzQ2ODcsImlzcyI6InJFRVN6TU5ZUlM2RnBWNnZlY09vdExPNWdPcUNXSmFQIiwiaWF0IjoxNTk4NDMxMDg3fQ.isQ40HqHHfJ-rTsUQOhRIdu4XCitZU-AfzeqSH4kPbQ',
            'XAPPKEY': 'f6b59b74-f943-4735-bb86-e05d6b7fd78e',
            'Source': 'GSB'
        },
        requestId: uuidv4()
    });
    console.log("resData--------------------------", JSON.stringify(resData));
    if (resData.status !== 0) {
        console.log("resData.msg--------------------------" + resData.msg + "-------------------------msg");
        throw new Error(resData.msg)
    }
}

/**
 * 确认做账服务完成
 * @param {*} bizId 
 * @param {*} data 
 */
const accountingFinishToRys = async (bizId, data) => {
    let resData = await system.queueOper({
        pushUrl: settings.rysUrl() + "/service/accounting/finish",
        actionType: "finish",
        messageBody: {
            BizNo: bizId,
            AccountDate: moment(data.initPeriod.toString()).format('YYYY-MM')
        },
        headData: {
            'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTg0MzQ2ODcsImlzcyI6InJFRVN6TU5ZUlM2RnBWNnZlY09vdExPNWdPcUNXSmFQIiwiaWF0IjoxNTk4NDMxMDg3fQ.isQ40HqHHfJ-rTsUQOhRIdu4XCitZU-AfzeqSH4kPbQ',
            'XAPPKEY': 'f6b59b74-f943-4735-bb86-e05d6b7fd78e',
            'Source': 'GSB'
        },
        requestId: uuidv4()
    });
    console.log("resData--------------------------", JSON.stringify(resData));
    if (resData.status !== 0) {
        console.log("resData.msg--------------------------" + resData.msg + "-------------------------msg");
        throw new Error(resData.msg)
    }
}

/**
 *  报税情况录入
 * @param {*} bizId 
 * @param {*} data 
 */
const taxSubmitToRys = async (bizId, data) => {

}

/**
 *  三大报表导入接口
 * @param {*} bizId 
 * @param {*} data 
 */
const financialStatementsToRys = async (bizId, data) => {

}

/**
 * 余额表导入接口
 * @param {*} bizId 
 * @param {*} data 
 */
const subjectBalanceToRys = async (bizId, data) => {

}



module.exports = {
    postToFtBySign,
    addCusAccApplyInfo,
    getChannelCompany,
    feedbackToRys,
    accountingFinishToRys,
    taxSubmitToRys,
    financialStatementsToRys,
    subjectBalanceToRys
}