package com.zjrs.ggfw.dzsbk.util;

import com.alibaba.csb.sdk.security.SignUtil;
import com.alibaba.fastjson.JSON;
import com.zjrs.ggfw.dzsbk.dto.PropertyDTO;
import com.zjrs.ggfw.dzsbk.dto.SignDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Kevin on 2018/6/7.
 */
public class SignUtils {
	
	private static final Logger LOG = LoggerFactory.getLogger(SignUtils.class);

    static String CHARSET_UTF_8 = "UTF-8";

    public static String sign(PropertyDTO propertyDTO,SignDTO signDTO) throws Exception {
        // 组装签名需要的参数
        Map<String, String> result = new HashMap<>();
        result.put("_api_name", "get_token");
        result.put("_api_version", "1.0.0");
        result.put("_api_access_key", propertyDTO.getAk());
        result.put("api_access_key", propertyDTO.getAk());
        result.put("_api_timestamp", System.currentTimeMillis() + "");
        result.put("return_url", signDTO.getReturnUrl());
        
        //自定义参数
        signDTO.setReturnUrl(null);
        signDTO.setChannelNo(propertyDTO.getChannelNo());//渠道号必录
        String bodyJson = JSON.toJSONString(signDTO);
        LOG.info("====sign自定义参数===="+bodyJson);
        //对请求参数进行DES3加密
        result.put("security", AESUtils.encrypt(bodyJson, propertyDTO.getDk()));
        
        //签名
        String sign = SignUtil.sign(result, propertyDTO.getSk());
        result.put("_api_signature", URLEncoder.encode(sign, CHARSET_UTF_8));
        
        // 签名之后对security和returnUrl进行URLEncoder，注意，一定要在签名后再URLEncoder
        result.put("security", URLEncoder.encode(result.get("security"), CHARSET_UTF_8));
        result.put("return_url", URLEncoder.encode(result.get("return_url"), CHARSET_UTF_8));

        // 将各签名参数拼接成一个字符串返回
        StringBuffer sb = new StringBuffer();
        result.entrySet().stream().forEach(es -> sb.append("&").append(es.getKey()).append("=").append(es.getValue()));
        String urlParams = sb.substring(1).toString();

        return urlParams;
    }

}
