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


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yc.ship.module.trade.framework.common.Base64Util;
import com.yc.ship.module.trade.framework.common.Md5;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

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

/**
 * @Title: SameWayUtil.java
 * @Package: com.wisesoft.scenic.api.resolver
 * &#064;Description: 通用接口认证工具类
 * @author: zhoulonggui
 * @date: 2017年5月18日 下午3:50:02
 * @version: V1.0
 * sign= md5(user_id+method+timestamp+version+requestBody+user_key)
 */
@Slf4j
public class ZshlAuthUtil {

    /**
     * 通用接口：请求json解密
     *
     * @param jsonObj
     * @param userKey
     * @return
     * @throws Exception
     * @author zhoulonggui
     * @date 2017年9月6日
     */
    public static Map<String, String> decodeRequestJson(JSONObject jsonObj, String userKey) throws UnsupportedEncodingException {
        Map<String, String> jsonMap = new HashMap<>(0);
        String bodyStr = "";
        // 解析类型
        int type = 0;
        if (jsonObj.containsKey("requestBody")) {
            bodyStr = jsonObj.getStr("requestBody");
        }
        if (jsonObj.containsKey("responseBody")) {
            type = 1;
            bodyStr = jsonObj.getStr("responseBody");
        }
        // requestBody 解密
        String body = "";
        try {
            body = DesUtil.decrypt(bodyStr, userKey);
        } catch (Exception e) {
            log.info(e.toString());
            throw new UnsupportedEncodingException("DES解密请求body异常,请检查密钥或者解析模式是否正确.");
        }
        jsonMap.put("requestHead", jsonObj.getStr("requestHead"));
        switch (type) {
            case 0:
                jsonMap.put("requestBodyNotDe", bodyStr);
                jsonMap.put("requestBody", body);
                break;
            case 1:
                jsonMap.put("responseBodyNotDe", bodyStr);
                jsonMap.put("responseBody", body);
                break;

        }
        return jsonMap;
    }

    /**
     * 通用接口：解析请求头
     *
     * @param jsonObj
     * @return return
     * @author zhoulonggui
     * @date 2017年5月18日
     */
    public static Map<String, String> parseRequestHead(JSONObject jsonObj) {
		/*{
	        "user_id": "815c2058-c7e5-4842-9489-2ede44758fd9", 
	        "method": "CreateOrder", 
	        "timestamp": 1458871246, 
	        "version": "v1.0", 
	        "sign": "3cb1c55d83cbe7ea232a5a7bd8dafeac"
	    }*/
        Map<String, String> requestHead = new HashMap<String, String>(0);
        requestHead.put("user_id", jsonObj.getStr("user_id"));
        requestHead.put("method", jsonObj.getStr("method"));
        requestHead.put("timestamp", jsonObj.getStr("timestamp"));
        requestHead.put("version", jsonObj.getStr("version"));
        requestHead.put("sign", jsonObj.getStr("sign"));
        return requestHead;
    }

    /**
     * 通用接口：sign校验
     *
     * @param headMap
     * @param userId
     * @param userKey
     * @param requestBody
     * @return
     * @throws UnsupportedEncodingException
     * @author zhoulonggui
     * @date 2017年5月18日
     */
    public static boolean checkSign(Map<String, String> headMap, String method, String userId, String userKey, String requestBody) throws UnsupportedEncodingException {
        //sign= md5(user_id+method+timestamp+version+requestBody+user_key)
        String signStr = userId + method + headMap.get("timestamp") + requestBody + userKey;
        String usSign = Md5.getMD5(signStr.getBytes("UTF-8"));
        String sign = headMap.get("sign");
        log.info("signStr:" + signStr);
        log.info("oldSign:" + sign);
        log.info("我方Sign:" + usSign);
        // 判断签名是否相同
        if (usSign.equals(sign)) {
            return true;
        }
        return false;
    }

    /**
     * 通用接口：生成sign
     *
     * @param requestHead
     * @param userId
     * @param userKey
     * @param requestBody
     * @return
     * @throws UnsupportedEncodingException
     * @author zhoulonggui
     * @date 2017年9月6日
     */
    public static String generateSign(JSONObject requestHead, String userId, String userKey, String requestBody) throws UnsupportedEncodingException {
        String signStr = userId + requestHead.get("method") + requestHead.get("timestamp") + requestBody + userKey;
        String sign = Md5.getMD5(signStr.getBytes("UTF-8"));
        //requestHead.put("sign", sign);
        log.info("signStr:" + signStr);
        log.info("生成的sign:" + sign);
        return sign;
    }

    /**
     * 校验帐号
     *
     * @param json
     * @param userId
     * @return
     * @author zhoulonggui
     * @date 2017年9月8日
     */
    public static boolean checkAccount(JSONObject json, String userId) {
        if (null == json) {
            return false;
        }
        String reqUid = json.getStr("user_id");
        if (StringUtils.isNotEmpty(reqUid) && StringUtils.isNotEmpty(userId)) {
            return reqUid.equals(userId);
        }
        return false;
    }


    /**
     * 解析返回数据
     *
     * @param jsonStr
     * @param userKey
     * @return
     * @throws Exception
     */
    public static Map<String, String> decodeResponseJson(String jsonStr, String userKey) throws Exception {

        // base64解密
        String json = Base64Util.decode(jsonStr);

        // 转为object
        JSONObject object = JSONUtil.parseObj(json);
        Map<String, String> jsonMap = new HashMap<String, String>(0);
        String requestBodyStr = object.getStr("responseBody");
        // requestBody 解密
        String bodyString = "";
        if (!"".equals(requestBodyStr)) {
            try {
                bodyString = DesUtil.decrypt(requestBodyStr, userKey);
            } catch (Exception e) {
                log.info(e.toString());
                throw new Exception("DES解密请求body异常,请检查密钥或者解析模式是否正确.");
            }
        }

        jsonMap.put("responseHead", object.getJSONObject("responseHead").toString());
        jsonMap.put("responseBody", bodyString);

        return jsonMap;
    }
}
