package com.uas.eis.core.support;

import com.uas.eis.dao.BaseDao;
import com.uas.eis.dao.SqlRowList;
import com.uas.eis.entity.ErrorMessage;
import com.uas.eis.exception.ApiSystemException;
import com.uas.eis.sdk.entity.ApiResult;
import com.uas.eis.utils.MD5Util;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.*;

@Service
public class MesHelperApiLoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private BaseDao baseDao;

    // 签名超时时长，默认时间为5分钟，ms
    private static final int SIGN_EXPIRED_TIME = 60 * 60 * 1000;
    private static final String ACCESS_KEY = "AccessKey";
    private static final String ACCESS_SECRET = "AccessSecret";
    private static final String TIMESTAMP_KEY = "Timestamp";
    private static final String SIGN_KEY = "Signature";
    private static final String RequestId = "RequestId";
    private static Map<String,String> tokenConfig = TokenProperties.getAllProperty();


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accessKey = "MES";
        String accessSecret = "394thg9egn8e9g";
        String requestId = request.getHeader(RequestId);

        // 检查KEY是否合理
        if (StringUtils.isEmpty(accessKey) || StringUtils.isEmpty(accessSecret)) {
            throw new ApiSystemException(new ApiResult(ErrorMessage.ACCESSKEY_ILLEGAL,requestId));
        }

        //改用中心账套表取账户密码
        SqlRowList rs = baseDao.queryForRowSet("select AE_SECRET from APIEMPLOYEE where AE_KEY=?",accessKey);
        if(rs.next()){
            if(!accessSecret.equals(rs.getString("AE_SECRET"))) {
                throw new ApiSystemException(new ApiResult(ErrorMessage.ACCESSSECRET_ERROR,requestId));
            }
        }else{
            throw new ApiSystemException(new ApiResult(ErrorMessage.ACCESSKEY_ERROR,requestId));
        }

        return true;
    }

    private boolean verificationSign(HttpServletRequest request, String accessKey, String accessSecret) throws UnsupportedEncodingException {
        Enumeration<?> pNames = request.getHeaderNames();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(ACCESS_KEY,request.getHeader(ACCESS_KEY));
        params.put(RequestId,request.getHeader(RequestId));
        params.put(TIMESTAMP_KEY,request.getHeader(TIMESTAMP_KEY));
        String originSign = request.getHeader(SIGN_KEY);
        String sign = createSign(params, accessSecret);
        System.out.println(sign);

        return sign.equals(originSign);
    }

    private String createSign(Map<String, Object> params, String accessSecret) throws UnsupportedEncodingException {
        Set<String> keysSet = params.keySet();
        Object[] keys = keysSet.toArray();
        Arrays.sort(keys);
        StringBuilder temp = new StringBuilder();
        boolean first = true;
        for (Object key : keys) {
            if (first) {
                first = false;
            } else {
                temp.append("&");
            }
            temp.append(key).append("=");
            Object value = params.get(key);
            String valueString = "";
            if (null != value) {
                valueString = String.valueOf(value);
            }
            temp.append(valueString);
        }
        temp.append("&").append(ACCESS_SECRET).append("=").append(accessSecret);
        System.out.println(temp);
        System.out.println(MD5Util.encrypt32Up(temp.toString()));
       // System.out.println(MD5Util.getEncryption(temp.toString()));
        return MD5Util.encrypt32Up(temp.toString()).toUpperCase();
    }
}
