package com.za.net;

import android.util.Base64;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.za.common.GlobalData;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * @author DoggieX
 * @create 2021/8/23 15:00
 * @mail coldpuppy@163.com
 */
public class RequestEncryptInterceptor implements Interceptor {

    static final String PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7UM6zdWdBuO0DZZVkxVfJioawUe6qH1p5Uz/qR9zbawl2oWyxxcBfxQyPS+HxOej/ZnyS4bu7qhh99alDqkJzk6g9oGZWs+jEF5GRWt9nChlfUsjvHQwuF2TSQMTdPtDPCByF/QgMFCAfbCqTrNmOETrZ/2GFy1Re0BTlhh6X/XzpzqtK+enikEMlQ5fIM5ljdXgyCnvDou9ptWqzw8Zmsat6LeA0UKz+bgpJAbw6KfK+8lPMqUpNFfkmJuEd5+JQOG9McH7j9pBagohkC6k3Cn92dAf9iD6NSDKSNgt1vxXhaNnfAbYJ5pqeSGy6QMSVO0TXYj4asln5OutD/284QIDAQAB";

    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
        String method = request.method().toLowerCase().trim();
        HttpUrl url = request.url();
        boolean skipEncrypt = url.encodedPath().endsWith("appVersion")
                || url.encodedPath().endsWith("getVerifyCode")
                || url.encodedPath().endsWith("listVehicleNew")
                || url.encodedPath().endsWith("getExitMileage")
                || url.encodedPath().endsWith("uploadImage")
                || url.encodedPath().endsWith("upload")
                || url.encodedPath().endsWith("matchAppUploadTime");

        if (method.equals("post") && !skipEncrypt) {
            RequestBody body = request.body();
            if (null != body) {
                Buffer buffer = new Buffer();
                body.writeTo(buffer);
                String data = URLDecoder.decode(buffer.readString(StandardCharsets.UTF_8), "utf-8");
                JSONObject jsonObject = JSON.parseObject(data);
                if (null == jsonObject) {
                    jsonObject = new JSONObject();
                }
                jsonObject.put("requestTime", System.currentTimeMillis());
                data = jsonObject.toJSONString();

                String aesKey;
                try {
                    if (url.encodedPath().endsWith("login")
                            || url.encodedPath().endsWith("fastLogin")) {
                        // 登录接口生成新key
                        aesKey = AESUtils.getRandomKey(16);
                        GlobalData.INSTANCE.setAesKey(aesKey);
                    } else {

                        aesKey = GlobalData.INSTANCE.getAesKey();
                        if (null == aesKey && url.encodedPath().endsWith("loginWithTask")) {
                            aesKey = AESUtils.getRandomKey(16);
                            GlobalData.INSTANCE.setAesKey(aesKey);
                        } else if (null == aesKey) {
                            throw new IOException("缺失加密密钥");
                        } else {
                            aesKey = GlobalData.INSTANCE.getAesKey();
                        }
                    }
                    if (!url.encodedPath().endsWith("login")
                            && !url.encodedPath().endsWith("fastLogin")
                            && !url.encodedPath().endsWith("loginWithTask")) {

                        data = AESUtils.encrypt(data, aesKey);
                    }
                    RequestBody requestBody = RequestBody.create(body.contentType(), data);
                    Request.Builder requestBuilder = request.newBuilder().post(requestBody);

                    if (url.encodedPath().endsWith("login")
                            || url.encodedPath().endsWith("fastLogin")
                            || url.encodedPath().endsWith("loginWithTask")) {

                        byte[] bytes = RSAUtils.encryptByPublicKey(aesKey.getBytes(StandardCharsets.UTF_8), PUBLIC_KEY);
                        String tokenSecret = Base64.encodeToString(bytes, Base64.NO_WRAP);
                        requestBuilder.addHeader("secret", tokenSecret);
                    } else {
                        String token = GlobalData.INSTANCE.getToken();
                        if (null == token) {
                            throw new IOException("缺失token");
                        } else {
                            requestBuilder.addHeader("token", token);
                        }
                    }
                    request = requestBuilder.build();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return chain.proceed(request);
    }
}
