package com.sheep.gamegroup.model.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kfzs.appstore.utils.string.HexUtils;
import com.sheep.gamegroup.model.entity.BaseMessage;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import go.kfzssafe.Kfzssafe;
import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by realicing on 2018/4/2.
 */
public class BaseMessageConverter implements Converter<ResponseBody, BaseMessage> {

    @Override
    public BaseMessage convert(ResponseBody value) throws IOException {
        String json = decrypt(value.string());
//        String json = value.string();
        BaseMessage baseMessage = JSONObject.parseObject(json, BaseMessage.class);
        return baseMessage;
    }


    /**
     * 加密
     * @param requestJson
     * @return
     */
    public static String encrypt(String requestJson){
        try {
            byte[] byteEncode = Kfzssafe.XByteEncode(requestJson.getBytes());
            return HexUtils.bytes2HexStr(byteEncode);
        } catch (Exception e) {
            e.printStackTrace();
            return requestJson;
        }
    }

    /**
     * 解密
     * @param respenseJson
     * @return
     */
    public static String decrypt(String respenseJson){
        if(respenseJson.startsWith("{")){
            return respenseJson;
        }
        try {
            byte[] bytes = HexUtils.hexStr2Bytes(respenseJson);
            byte[] byteDecode = Kfzssafe.XByteDecode(bytes);
            return new String(byteDecode);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String,String> map = new HashMap<>();
            map.put("msg",respenseJson);
            return JSON.toJSONString(map);
        }
    }
}
