package com.ajb.global.authorize.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ajb.global.authorize.service.AuthorizeService;
import com.ajb.global.authorize.util.AudienceSetting;
import com.ajb.global.authorize.util.JwtTokenUtil;
import com.ajb.global.authorize.vo.CheckTokenRequestVO;
import com.ajb.car.vo.common.CommonResult;
import com.ajb.common.utils.string.CommonUtil;
import com.ajb.global.enums.ParamVerifyEnum;
import com.ajb.global.enums.ResultEnum;
import com.ajb.global.authorize.vo.CheckTokenResponseVO;
import com.ajb.global.authorize.vo.ObtainTokenRequestVO;
import com.ajb.global.authorize.vo.ObtainTokenResponseVO;


@Service("authorizeService")
public class AuthorizeServiceImpl implements AuthorizeService {
	@Autowired
	private JwtTokenUtil jwtTokenUtil;
	@Autowired
	private AudienceSetting audienceSetting;
	
	@Override
	public ObtainTokenResponseVO obtainToken(ObtainTokenRequestVO requestVO) {
		boolean success = true;
		String message = ResultEnum.QUERY_SUCCESS.getMessage();
		ObtainTokenResponseVO responseVO = new ObtainTokenResponseVO();
		if(requestVO == null || CommonUtil.isNullOrBlank(requestVO.getTicket())){
			responseVO.setCommonResult(new CommonResult(false,ParamVerifyEnum.PARAM_NOT_NULL.getMessage()));
			return responseVO;
		}
		String token = jwtTokenUtil.generateToken(requestVO.getTicket());
		responseVO.setToken(token);

		responseVO.setCommonResult(new CommonResult(success,message));
		
		return responseVO;
	}

	@Override
	public CheckTokenResponseVO checkToken(CheckTokenRequestVO requestVO) {
		boolean success = true;
		String message = "校验通过";
		CheckTokenResponseVO responseVO = new CheckTokenResponseVO();

		if(requestVO == null || CommonUtil.isNullOrBlank(requestVO.getToken())){
			responseVO.setCommonResult(new CommonResult(false,ParamVerifyEnum.PARAM_NOT_NULL.getMessage()));
			return responseVO;
		}
		String token = requestVO.getToken();
		if(token.startsWith(audienceSetting.issuer)){
			token = token.substring(audienceSetting.issuer.length()+1);
		}
		boolean isTokenValid = jwtTokenUtil.validateToken(token);
		boolean isTokenExpired = jwtTokenUtil.isTokenExpired(token);
		if(isTokenExpired){
			success = false;
			message = "token已失效！";
		}else if(isTokenValid){
			String ticket = requestVO.getTicket();
			if(!CommonUtil.isNullOrBlank(ticket)){
				boolean valid = jwtTokenUtil.validateToken(token, ticket);
				if(!valid){
					success = false;
					message = "由token解析出的ticket和传入的ticket不一致！";
				}
			}
		}else{
			success = false;
			message = "token格式不合法！";
		}
		responseVO.setCommonResult(new CommonResult(success,message));
		return responseVO;
	}

}
