package com.backendsys.modules.sdk.baidu.yunapp.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.backendsys.exception.CustException;
import com.backendsys.modules.sdk.baidu.yunapp.entity.YuappSign;
import org.springframework.stereotype.Component;

import javax.crypto.*;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;

@Component
public class YunappUtil {

    private String DES_KEY = "df22190e23e1e3c139c26508f44526b6";
    private String APP_KEY = "4988d7dcafdc46edbb15b141892d5986";
    private String APP_SECRET = "dbd12e4165f8b81ed4866e392201bc4f";
    private Integer AUTH_VER = 3;

    /**
     * 生成签名
     */
    public YuappSign getSign() {
        Long nonce = System.currentTimeMillis();
        String paramsStr = "appkey" + APP_KEY + "auth_ver" + AUTH_VER + "nonce" + nonce + APP_SECRET;
        String sign = org.apache.commons.codec.digest.DigestUtils.md5Hex(paramsStr.getBytes(StandardCharsets.UTF_8));
        YuappSign entity = new YuappSign();
        entity.setS(sign);
        entity.setApp_key(APP_KEY);
        entity.setAuth_ver(AUTH_VER);
        entity.setNonce(nonce);
        return entity;
    }

    /**
     * 加密参数
     */
    public String getMsg(String requestParam, Long nonce) {
        try {

            // 请求参数加密
            Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
            SecretKeyFactory skf = SecretKeyFactory.getInstance("DESede");
            SecretKey secretKey = skf.generateSecret(new DESedeKeySpec(DES_KEY.getBytes(StandardCharsets.UTF_8)));
            ByteBuffer byteBuffer = ByteBuffer.allocate(8);
            byteBuffer.order(ByteOrder.BIG_ENDIAN);
            byteBuffer.putLong(nonce);
            byte[] iv = byteBuffer.array();
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
            byte[] cipherText = cipher.doFinal(requestParam.getBytes(StandardCharsets.UTF_8));
            String msg = Base64.getEncoder().encodeToString(cipherText);
            return msg;

        } catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException |
                 InvalidAlgorithmParameterException | IllegalBlockSizeException |
                 InvalidKeySpecException | BadPaddingException e) {
            throw new CustException(e.getMessage());
        }
    }

    /**
     * 格式化返回值
     * { data, code, msg, ts }
     */
    public JSONObject getResponseJSONObject(String body) {
        JSONObject responseBody = JSONUtil.parseObj(body);
        Integer code = Convert.toInt(responseBody.get("code"));
        String msg = Convert.toStr(responseBody.get("msg"));
        if (code == 0) {
            return JSONUtil.parseObj(responseBody.get("data"));
        } else {
            throw new CustException(msg);
        }
    }
    public JSONArray getResponseJSONArray(String body) {
        JSONObject responseBody = JSONUtil.parseObj(body);
        Integer code = Convert.toInt(responseBody.get("code"));
        String msg = Convert.toStr(responseBody.get("msg"));
        if (code == 0) {
            return JSONUtil.parseArray(responseBody.get("data"));
        } else {
            throw new CustException(msg);
        }
    }

}
