package com.cftech.invoice.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.core.util.SystemConfig;
import com.cftech.invoice.model.Invoice;
import lombok.extern.slf4j.Slf4j;
import nuonuo.open.sdk.NNOpenSDK;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * Created by 16444 on 2020/12/23.
 */
@Slf4j
@Component
public class InvoiceHttpUtil {

    //授权企业税号
    private static String taxNum = SystemConfig.p.getProperty("INVOICE_TAX");

    //appkey
    private static String appKey = SystemConfig.p.getProperty("APP_KEY");

    //appSecrt
    private static String appSecret = SystemConfig.p.getProperty("APP_SECRET");

    //访问令牌
    private static String token = SystemConfig.p.getProperty("INVOICE_TOKEN");

    //SDK请求地址
    private static String url = SystemConfig.p.getProperty("INVOICE_URL");

    private static String genarateUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static String queryInvoiceResult(Invoice invoice) {
        JSONObject params = new JSONObject();
        params.put("serialNos", new String[]{invoice.getInvoiceSerialNum()});
        params.put("isOfferInvoiceDetail", "0");//提供发票明细

        String method = SystemConfig.p.getProperty("INVOICE_QUERY_API");
        NNOpenSDK sdk = NNOpenSDK.getIntance();
        String result = sdk.sendPostSyncRequest(url, genarateUUID(), appKey, appSecret, token, taxNum, method, params.toString());
        log.info("发票结果查询" + result);
        return result;
    }

    public static String deliveryInvoice(Invoice invoice, String email) {
        JSONObject params = new JSONObject();
        params.put("taxnum", taxNum);
        params.put("invoiceCode", invoice.getInvoiceCode());//发票代码
        params.put("invoiceNum", invoice.getInvoiceNum());//发票号码
        params.put("mail", email);

        String method = SystemConfig.p.getProperty("INVOICE_SEND_EMAIL_API");
        NNOpenSDK sdk = NNOpenSDK.getIntance();
        String result = sdk.sendPostSyncRequest(url, genarateUUID(), appKey, appSecret, token, taxNum, method, params.toString());
        log.info("发票结果查询" + result);
        return result;
    }
}
