package com.dxhy.erp.utils;

import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.alibaba.fastjson.JSONObject;
import com.dxhy.erp.entity.CheckInvoiceParam;
import com.dxhy.erp.entity.ReqData;
import com.dxhy.erp.entity.RequestXml;

import cn.hutool.core.codec.Base64;
import lombok.extern.slf4j.Slf4j;

/**
 * @author dxhy
 */
@Slf4j
public class CheckHmacsha1Util {

    private static final String SECRET_KEY = "ccf747a9242a43f69b4dc5b35541a3b6";

    private static final String SECRET_ID = "ec4f1972a5c94bf0b67a1c03e8324d3d";
    // ec4f1972a5c94bf0b67a1c03e8324d3d

    public static String getHmacsha1(CheckInvoiceParam checkInvoiceParam) throws Exception {
        RequestXml requestXml = new RequestXml();
        double a = Math.random();
        int random = (int)(a * 100000);
        requestXml.setNonce(random + "");
        requestXml.setSecretId(SECRET_ID);
        requestXml.setContent(getData(checkInvoiceParam));
        requestXml.setTimestamp(System.currentTimeMillis() + "");
        requestXml.setEncryptCode("0");
        requestXml.setZipCode("0");
        String sb =
            "POST/recipt/checkFp/barcode?" + "nonce=" + requestXml.getNonce() + "&secretId=" + requestXml.getSecretId()
                + "&timestamp=" + requestXml.getTimestamp() + "&content=" + requestXml.getContent() + "&encryptCode="
                + requestXml.getEncryptCode() + "&zipCode=" + requestXml.getZipCode();
        String hmacsha1 = CheckHmacsha1Util.hmacsha1(sb, SECRET_KEY);
        requestXml.setSignature(hmacsha1);
        return JSONObject.toJSONString(requestXml);
    }

    /**
     * HmacSHA1生成签名值
     *
     * @param data
     *            数据
     * @param key
     *            密钥
     * @return 签名值
     */
    private static String hmacsha1(String data, String key) {
        byte[] keyData = key.getBytes(StandardCharsets.UTF_8);
        try {
            SecretKeySpec signingKey = new SecretKeySpec(keyData, "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);
            byte[] doFinal = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return Base64.encode(doFinal);
        } catch (NoSuchAlgorithmException e) {
            log.error("NoSuchAlgorithmException", e);
        } catch (InvalidKeyException e) {
            log.error("InvalidKeyException", e);
        } catch (Exception e) {
            log.error("未知异常", e);
        }
        return null;
    }

    /**
     *
     * base64后的数据项
     *
     * @param checkInvoiceParam
     * @return String
     * @throws Exception
     * @author X Yang
     * @date 2017年8月4日 上午11:30:59
     */
    public static String getData(CheckInvoiceParam checkInvoiceParam) throws Exception {
        ReqData data = new ReqData();
        data.setCheckType("dz");
        data.setData(getReqXml(checkInvoiceParam));
        data.setTaxpayertId("91110000717740639D");
        data.setType("jxxt_yl");
        String json = JSONObject.toJSONString(data);
        return Base64.encode(json);
    }

    /**
     *
     * 发票内容
     *
     * @param checkInvoiceParam
     * @return String
     * @author X Yang
     * @date 2017年8月4日 上午11:34:14
     */
    public static String getReqXml(CheckInvoiceParam checkInvoiceParam) {

        return "<?xml version='1.0' encoding='utf-8' ?>" + "<FPXT><REQUEST_CONTENT><FP><PDF/><PDF_MD5/>" + "<FPLX>"
            + checkInvoiceParam.getInvoiceType() + "</FPLX>" + "<FPDM>" + checkInvoiceParam.getInvoiceCode() + "</FPDM>"
            + "<FPHM>" + checkInvoiceParam.getInvoiceNo() + "</FPHM>" + "<KPRQ>" + checkInvoiceParam.getInvoiceDate()
            + "</KPRQ>" + "<JYM>" + checkInvoiceParam.getCheckCode() + "</JYM>" + "<BHSJE>"
            + checkInvoiceParam.getInvoiceAmount() + "</BHSJE>" + "<SJH></SJH>" + "</FP></REQUEST_CONTENT></FPXT>";
    }
}
