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.accountPeriod.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) => {
    let resData = await system.queueOper({
        pushUrl: settings.rysUrl() + "/service/tax/submit",
        actionType: "submit",
        messageBody: {
            BizNo: bizId,
            "AccountDate": moment(data.taxPeriod.toString()).format('YYYY-MM'),
            "ValueAddedTax": data.addedTaxAmount,
            "SuperTax": data.additionalTaxAmount,
            "EnterpriseIncomeTax": data.incomeTaxAmount,
            "StampTax": data.stampTaxAmount,
            "LabourUnionExpense": data.labourUnionExpenditure,
            "FoundationForWaterWorks": data.waterConservancyFunds,
            "DisabilityInsuranceFund": data.disabilityInsuranceFunds,
            "OtherTax": data.otherAmount
        },
        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 financialStatementsToRys = async (bizId, data) => {
    let [BalanceSheetData, ProfitData, CashFlowData] = await Promise.all([
        postToFtBySign('/report/getReportData', {
            companyId: data.companyId,
            customerId: data.customerId,
            accountPeriod: data.accountPeriod,
            reportType: 1
        }),
        postToFtBySign('/report/getReportData', {
            companyId: data.companyId,
            customerId: data.customerId,
            accountPeriod: data.accountPeriod,
            reportType: 2
        }),
        postToFtBySign('/report/getReportData', {
            companyId: data.companyId,
            customerId: data.customerId,
            accountPeriod: data.accountPeriod,
            reportType: 3
        })
    ]);
    let resData = await system.queueOper({
        pushUrl: settings.rysUrl() + "/reportImport/FinancialStatements",
        actionType: "FinancialStatements",
        messageBody: {
            BizNo: bizId,
            ReportYear: parseInt(data.accountPeriod.toString().slice(0, 4)),
            ReportMonth: parseInt(data.accountPeriod.toString().slice(4)),
            BalanceSheetData: BalanceSheetData.reportData.filter(item => {
                return item.lineNo !== 0;
            }).map(item => {
                return {
                    "LineNo": item.lineNo,
                    "EndBalance": (item.value[0] || 0).toFixed(2),
                    "YearStartBalance": (item.value[1] || 0).toFixed(2)
                }
            }),
            ProfitData: ProfitData.reportData.filter(item => {
                return item.lineNo !== 0;
            }).map(item => {
                return {
                    "LineNo": item.lineNo,
                    "MonthAmount": (item.value[0] || 0).toFixed(2),
                    "YearAmount": (item.value[1] || 0).toFixed(2)
                }
            }),
            CashFlowData: CashFlowData.reportData.filter(item => {
                return item.lineNo !== 0;
            }).map(item => {
                return {
                    "LineNo": item.lineNo,
                    "MonthAmount": (item.value[0] || 0).toFixed(2),
                    "YearAmount": (item.value[1] || 0).toFixed(2)
                }
            })
        },
        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 subjectBalanceToRys = async (bizId, data) => {
    let reqData = await postToFtBySign('/accAbvlists', {
        companyId: data.companyId,
        customerId: data.customerId,
        end: data.accountPeriod.toString(),
        isDetailed: false,
        start: data.accountPeriod.toString(),
    });
    let { treeResponseList } = reqData;
    let Total = treeResponseList["700"];
    let treeResponseArry = [];
    for (let key in treeResponseList) {
        if (key != "700") {
            let newArry = [];
            buildSubjectBalancData(treeResponseList[key], newArry);
            treeResponseArry.push(...newArry);
        }
    }
    let resData = await system.queueOper({
        pushUrl: settings.rysUrl() + "/reportImport/SubjectBalance",
        actionType: "SubjectBalance",
        messageBody: {
            BizNo: bizId,
            AccountYear: parseInt(data.accountPeriod.toString().slice(0, 4)),
            AccountMonth: parseInt(data.accountPeriod.toString().slice(4)),
            BalanceData: {
                Total: {
                    "EndBalanceTotalCreditValue": buildDoubleNumber(Total.rootCode),//期末贷方金额
                    "EndBalanceTotalDebitValue": buildDoubleNumber(Total.endBalance),//期末借方金额
                    "NowBalanceTotalCreditValue": buildDoubleNumber(Total.credit),//本期贷方金额
                    "NowBalanceTotalDebitValue": buildDoubleNumber(Total.dedit),//本期借方金额
                    "StartBalanceTotalCreditValue": buildDoubleNumber(Total.code),//期初贷方金额
                    "StartBalanceTotalDebitValue": buildDoubleNumber(Total.beginBalance),//期初借方金额
                    "VoucherNum": 0,//总凭证数
                    "YearBalanceTotalCreditValue": buildDoubleNumber(Total.ytdDedit),//本年累计借方金额
                    "YearBalanceTotalDebitValue": buildDoubleNumber(Total.ytdCedit)//本年累计贷方金额
                },
                List: treeResponseArry,
                TotalNum: treeResponseArry.length
            }

        },
        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 paperPostConfirmToRys = async (bizId, data) => {
    let resData = await system.queueOper({
        pushUrl: settings.rysUrl() + "/service/paperPost/confirm",
        actionType: "confirm",
        messageBody: {
            BizNo: bizId,
            "AccountDate": moment(data.currentPeriod.toString()).format('YYYY-MM'),
            "Status": data.status,
            "ErrorStatus": "",
            "Remark": data.remark
        },
        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)
    }
}

const buildDoubleNumber = (data) => {
    return data && Number(data) || 0.00
}

/**
 * 构建 余额表数据
 * @param {*} arry 
 * @param {*} newArry 
 */
const buildSubjectBalancData = (arry, newArry, i = 1) => {
    for (let val of arry) {
        newArry.push({
            "ActSubjectCode": val.accountCode,//科目code
            "ActSubjectName": val.accountName,//科目名称
            "ActSubjectDirection": Number(val.dc),//1借，-1贷，0 平
            "ActSubjectLevel": i,//科目层级
            "EndBalanceCredit": Number(val.dc) === -1 ? val.endBalance.toFixed(2) : "",//期末贷方金额
            "EndBalanceDebit": Number(val.dc) === 1 ? val.endBalance.toFixed(2) : "",//期末借方金额
            "NowBalanceCredit": val.credit.toFixed(2),//本期贷方金额
            "NowBalanceDebit": val.dedit.toFixed(2),//本期借方金额
            "StartBalanceCredit": Number(val.dc) === -1 ? val.beginBalance.toFixed(2) : "",//期初贷方金额
            "StartBalanceDebit": Number(val.dc) === 1 ? val.beginBalance.toFixed(2) : "",//期初借方金额
            "YearBalanceCredit": val.ytdCedit.toFixed(2),//本年贷方金额
            "YearBalanceDebit": val.ytdDedit.toFixed(2)// 本年借方金额
        })
        if (val.leafNodes.length > 0) {
            buildSubjectBalancData(val.leafNodes, newArry, i + 1)
        }
    }
}

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