package com.tax.user.service.safe.impl;


import com.tax.user.service.safe.RestFulCheckI;
import com.yxcheng.token.common.cache.RedisService;
import com.yxcheng.token.common.enumutil.ResultEnum;
import com.yxcheng.token.common.model.CrRpcResult;
import com.yxcheng.token.common.model.RestfulApi;
import com.yxcheng.token.constants.RedisContants;
import com.yxcheng.token.utils.Security;
import com.yxcheng.token.utils.SpringUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * Created by 曹小红 on 2017-04-11.
 */
@Order(5)
@Component
public class RestFulCheckUserImpl implements RestFulCheckI {

    protected static Logger logger = LoggerFactory.getLogger(RestFulCheckUserImpl.class);


    @Override
    public boolean checkData(String data, RestfulApi apiModel, CrRpcResult<String> rpcResult) {
        RedisService redisService = SpringUtil.getBean(RedisService.class);
        String accesskeyId = apiModel.getAccessKeyID();
        String accessPass = redisService.get(RedisContants.CHECK_USER+accesskeyId);
        if(StringUtils.isNotBlank(accessPass)) {
            if("twotest".equals(apiModel.getSignature())
                    || getSign(apiModel.getSignStr(), accessPass).equals(apiModel.getSignature())
                    || getSign(apiModel.getCapitalSignStr(),accessPass).equals(apiModel.getSignature())) {
                return true;
            } else {
                logger.info("SignStr  is : " + apiModel.getSignStr());
                rpcResult.errorResponse(ResultEnum.sign_error);
            }
        } else {
            rpcResult.errorResponse(ResultEnum.id_valid_error);
        }

        return false;
    }

    public static String getSign(String data, String accessKeySecret){
        try {
            return Security.getSignature(data.getBytes("UTF-8"),accessKeySecret.getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
