package com.fs.nuonuo;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fs.common.exception.base.BaseException;
import com.fs.common.utils.date.DateUtil;
import com.fs.nuonuo.vo.InvoiceRedVo;
import com.fs.nuonuo.vo.InvoiceResultVo;
import nuonuo.open.sdk.NNOpenSDK;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

public class NuonuoUtils {

    private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    private final static String KEY = "10924508";
    private final static String SECRET = "A2EB20764D304D16";
    private final static String BASE_URL = "https://sdk.nuonuo.com/open/v1/services";
    private final static String TOKEN = "7c5d284cc10f344b8198bb02zvijkmcs";

    private static JSONObject sendApi(String senid, String method, String content){
        NNOpenSDK sdk = NNOpenSDK.getIntance();
        String json = sdk.sendPostSyncRequest(BASE_URL, senid, KEY, SECRET, TOKEN, "91510115MABYRCJE31", method, content); // 请求API
        JSONObject result = JSONObject.parseObject(json);
        if(!"E0000".equals(result.getString("code"))){
            throw new BaseException("开票异常：" + result);
        }
        return result;
    }

    /**
     * 开票
     * @param uid        订单编号（后续查询使用）
     * @param buyerName  购放名称
     * @param buyerTaxNum  购放税号
     * @param price      金额
     * @param remark     备注
     * @return 发票订单流水号
     */
    public static String requestBilling(String uid, String buyerName, String buyerTaxNum, BigDecimal price, String remark){
        ObjectNode object = OBJECT_MAPPER.createObjectNode();
        ObjectNode put = object.putObject("order")
                .put("buyerName", buyerName)
                .put("buyerTaxNum", buyerTaxNum)
                .put("salerTaxNum", "91510115MABYRCJE31")
                .put("orderNo", uid)
                .put("invoiceDate", DateUtil.formatLocalDateTime(LocalDateTime.now()))
                .put("clerk", "666")
                .put("pushMode", -1)
                .put("invoiceLine", "pc")
                .put("salerAddress", "pc")
                .put("remark", remark)
                .put("callBackUrl", "http://219.152.207.209:9810/prod-api/invoice/scan")
                .put("invoiceType", 1);
        ArrayNode invoiceDetail = put.putArray("invoiceDetail");
        invoiceDetail.add(OBJECT_MAPPER.createObjectNode()
                .put("goodsName", "*医疗服务*会诊收入")
                .put("goodsCode", "3070202000000000000")
                .put("unit", "人")
                .put("specType", "无")
                .put("withTaxFlag", 0)
                .put("price", price)
                .put("num", 1)
                .put("taxRate", 0)
                .put("favouredPolicyFlag", "03")
        );
        String senid = UUID.randomUUID().toString().replace("-", "");
        JSONObject result = sendApi(senid, "nuonuo.OpeMplatform.requestBillingNew", object.toString());
        return result.getJSONObject("result").getString("invoiceSerialNum");
    }

    /**
     * 查询发票信息
     * @param orderNo 订单编号
     * @return 发票详情信息
     */
    public static List<InvoiceResultVo> queryInvoiceResult(List<String> orderNo){
        ObjectNode object = OBJECT_MAPPER.createObjectNode();
        String senid = UUID.randomUUID().toString().replace("-", "");
        object.put("isOfferInvoiceDetail", 1);
        ArrayNode orderNos = object.putArray("orderNos");
        orderNo.forEach(orderNos::add);
        JSONObject result = sendApi(senid, "nuonuo.OpeMplatform.queryInvoiceResult", object.toString());
        return result.getJSONArray("result").toJavaList(InvoiceResultVo.class);
    }

    /**
     * 冲红申请接口
     * @param invoiceNumber   发票号码
     * @param redReason       冲红原因： 1销货退回 2开票有误 3服务中止 4销售折让
     * @param buyerName       买方名称
     * @return 冲红申请单号
     */
    public static String saveInvoiceRedConfirm(String invoiceNumber, Integer redReason, String buyerName){
        ObjectNode object = OBJECT_MAPPER.createObjectNode();
        String senid = UUID.randomUUID().toString().replace("-", "");
        object.put("billId", "");
        object.put("blueInvoiceLine", "pc");
        object.put("applySource", "0");
        object.put("blueInvoiceNumber", "");
        object.put("blueInvoiceCode", "");
        object.put("blueElecInvoiceNumber", invoiceNumber);
        object.put("billTime", "");
        object.put("sellerName", "");
        object.put("departmentId", "");
        object.put("clerkId", "");
        object.put("buyerTaxNo", "");
        object.put("buyerName", buyerName);
        object.put("vatUsage", "");
        object.put("saleTaxUsage", "");
        object.put("accountStatus", "");
        object.put("redReason", redReason);
        object.put("autoInvoice", "0");
        object.put("extensionNumber", "");
        object.put("phone", "");
        object.put("email", "");
        object.put("sellerTaxNo", "91510115MABYRCJE31");
        object.put("callBackUrl", "http://219.152.207.209:9810/prod-api/invoice/scan");
        object.putArray("detail");
        JSONObject result = sendApi(senid, "nuonuo.OpeMplatform.saveInvoiceRedConfirm", object.toString());
        return result.getString("result");
    }
    /**
     * 红字确认单查询接口
     * @param invoiceNumber   发票号码
     * @return 冲红列表
     */
    public static List<InvoiceRedVo> queryInvoiceRedConfirm(String invoiceNumber){
        ObjectNode object = OBJECT_MAPPER.createObjectNode();
        String senid = UUID.randomUUID().toString().replace("-", "");
        object.put("identity", 0);
        object.put("blueInvoiceLine", "pc");
        object.put("blueElecInvoiceNumber", invoiceNumber);
        object.put("taxNum", "91510115MABYRCJE31");
        JSONObject result = sendApi(senid, "nuonuo.OpeMplatform.queryInvoiceRedConfirm", object.toString());
        return result.getJSONObject("result").getJSONArray("list").toJavaList(InvoiceRedVo.class);
    }
    /**
     * 快捷冲红接口
     * @param orderNo  平台订单号
     * @param billNo   冲红订单编号
     * @param billUuid 冲红uuid
     * @return 三方业务订单号
     */
    public static String fastInvoiceRed(String orderNo, String billNo, String billUuid){
        ObjectNode object = OBJECT_MAPPER.createObjectNode();
        String senid = UUID.randomUUID().toString().replace("-", "");
        object.put("orderNo", orderNo);
        object.put("billNo", billNo);
        object.put("billUuid", billUuid);
        object.put("taxNum", "91510115MABYRCJE31");
        object.put("callBackUrl", "http://219.152.207.209:9810/prod-api/invoice/scan");
        JSONObject result = sendApi(senid, "nuonuo.OpeMplatform.fastInvoiceRed", object.toString());
        return result.getJSONObject("result").getString("invoiceSerialNum");
    }

    public static void main(String[] args) {
        String uid = UUID.randomUUID().toString().replace("-", "");
//        String s = requestBilling(uid, "吴树波", BigDecimal.valueOf(1400), 1, "测试人员", "吴树波");
//        List<InvoiceResultVo> invoiceResultVos = queryInvoiceResult(Arrays.asList("6056991279"));
//        System.out.println(invoiceResultVos);
        List<InvoiceRedVo> invoiceRedVos = queryInvoiceRedConfirm("25512000000005127783");
        System.out.println(invoiceRedVos);
//        invoiceRedVos.forEach(e -> {
//            String s = fastInvoiceRed(uid, e.getBillNo(), e.getBillUuid());
//            System.out.println(s);
//        });
//        invoiceResultVos.forEach(e -> {
    //            saveInvoiceRedConfirm(e.getInvoiceNo() ,2, e.getPayerName());
//        });


    }


}
