package com.yc.ship.module.trade.framework.common.ota;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Base64Util;

@Slf4j
public class TongChengResponse {

    /**
     * 通用处理返回方法
     * @param res_code
     * @param res_msg
     * @param userKey
     * @return
     */
    public static String create(String res_code,String res_msg,String userKey){
        return create(res_code,res_msg,new JSONObject(),userKey);
    }

    /**
     * 通用处理返回方法
     * @param res_code
     * @param res_msg
     * @param body
     * @return
     */
    public static String create(String res_code, String res_msg, JSONObject body, String userKey){
        JSONObject result=null;
        try{
            JSONObject rep_head=new JSONObject();
            rep_head.put("res_code", res_code);
            rep_head.put("res_msg", res_msg);
            rep_head.put("timestamp", System.currentTimeMillis()/1000);
            result=new JSONObject();
            result.put("responseHead", rep_head);
            result.put("responseBody",DesUtil.encrypt(body.toString(),userKey));
            return Base64Encoder.encode(result.toString());
        }catch (Exception ex){
            log.error("返回同程信息加密失败："+result.toString());
            return "加密失败";
        }
    }

    /**
     * 还回数据签名
     * @param method
     * @param userId
     * @param userKey
     * @param req_body
     * @return
     */
    public static String sign(String method,String userId,String userKey,JSONObject req_body){
        try{
            JSONObject requestHead=new JSONObject();
            requestHead.put("user_id", userId);
            requestHead.put("method", method);//"ConsumeNotice"
            requestHead.put("timestamp", System.currentTimeMillis()/1000);
            requestHead.put("version", "v1.0");
            String requestBody=req_body.toString();
            String desBody = DesUtil.encrypt(requestBody,userKey);
            JSONObject json=new JSONObject();
            requestHead.put("timestamp",System.currentTimeMillis()/1000);
            requestHead.put("sign", TongChengAuthUtil.generateSign(requestHead,userId, userKey, desBody));
            json.put("requestHead",requestHead);
            json.put("requestBody",desBody);
            String result = Base64Util.encode(json.toString());
            return  result;
        }catch (Exception ex){
            return "";
        }
    }
}
