package com.uas.eis.core.support;

import com.uas.eis.core.config.SpObserver;
import com.uas.eis.dao.BaseDao;
import com.uas.eis.dao.SqlRowList;
import com.uas.eis.entity.ErrorMessage;
import com.uas.eis.entity.ErrorMsg;
import com.uas.eis.exception.ApiStepWorkException;
import com.uas.eis.exception.ApiSystemException;
import com.uas.eis.exception.SystemException;
import com.uas.eis.sdk.entity.ApiResult;
import com.uas.eis.sdk.entity.StepWorkApiResult;
import com.uas.eis.utils.MD5Util;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

public class ApiStepWorkInterceptor 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 BLADEAUTH = "Blade-Auth";
    private static final String AUTHORIZATION = "Authorization";

    private static final String AUTHDATA = "Basic c3dvcmQ6c3dvcmRfc2VjcmV0";


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        String token = request.getHeader(BLADEAUTH);
        String Authorization = request.getHeader(AUTHORIZATION);
        if(!AUTHDATA.equals(Authorization)){
            throw new ApiStepWorkException(new StepWorkApiResult(ErrorMessage.AUTHOR_ILLEGAL));
        }
        Claims claims =  parseToken(token);
        String username = (String) claims.get("username");
        String password = (String) claims.get("password");
        checkUser(username, password); // 验证用户是否合法
        HttpSession session = request.getSession();
        session.setAttribute("usercode",username);
        return true;
    }

    private void checkUser(String username, String password) {
        SqlRowList rs = baseDao.queryForRowSet("select AE_SECRET,AE_MASTER from APIEMPLOYEE where AE_KEY=?",username);
        if(rs.next()){
            if(!password.equals(rs.getString("ae_secret"))){
                throw new ApiStepWorkException(new StepWorkApiResult(ErrorMessage.ACCESSSECRET_ERROR));
            }else{
               SpObserver.putSp(rs.getString("ae_master"));
            }
        }else{
            throw new ApiStepWorkException(new StepWorkApiResult(ErrorMessage.ACCESSKEY_ERROR));
        }
    }


    private Claims parseToken(String token) {
        if(StringUtils.isEmpty(token) || !token.startsWith("bearer")){
            throw new ApiStepWorkException(new StepWorkApiResult(ErrorMessage.TOKEN_ILLEGAL));
        }
        token = token.substring(7);
        Claims claims = TokenHandler.parseToken(token);
        if(claims == null) {
            throw new ApiStepWorkException(new StepWorkApiResult(ErrorMessage.INVALID_TOKEN));
        }
        Date now = new Date();
        Date start = claims.getNotBefore();
        Date end = claims.getExpiration();

        if (now.after(start) && now.before(end)) {
            return claims;
        }else {
            throw new ApiStepWorkException(new StepWorkApiResult(ErrorMessage.EXPIRED_TOKEN));
        }
    }


}
