package com.yd.util.auth.service;

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

import com.yd.api.result.CommonResult;
import com.yd.util.CommonUtil;
import com.yd.util.auth.setting.AudienceSetting;
import com.yd.util.auth.setting.JwtTokenUtil;
import com.yd.util.auth.vo.CheckTokenRequestVO;
import com.yd.util.auth.vo.CheckTokenResponseVO;
import com.yd.util.auth.vo.ObtainTokenRequestVO;
import com.yd.util.auth.vo.ObtainTokenResponseVO;
import com.yd.util.config.ZHBErrorConfig;

@Service("authorizeService")
public class AuthorizeServiceImpl implements AuthorizeService {
	@Autowired
	private JwtTokenUtil jwtTokenUtil;
	@Autowired
	private AudienceSetting audienceSetting;
	
	@Override
	public ObtainTokenResponseVO obtainToken(ObtainTokenRequestVO requestVO) {
		ObtainTokenResponseVO responseVO = new ObtainTokenResponseVO();
		//入参校验
		if(requestVO == null || CommonUtil.isNullOrBlank(requestVO.getTicket())){
			responseVO.setCommonResult(new CommonResult(false,ZHBErrorConfig.getErrorInfo("600001")));
			return responseVO;
		}
		//获取TOKEN
		String token = jwtTokenUtil.generateToken(requestVO.getTicket());
		responseVO.setToken(token);
		responseVO.setCommonResult(new CommonResult(true,ZHBErrorConfig.getErrorInfo("800000")));
		return responseVO;
	}

	@Override
	public CheckTokenResponseVO checkToken(CheckTokenRequestVO requestVO) {
		boolean success = true;
		String message = ZHBErrorConfig.getErrorInfo("600000");
		CheckTokenResponseVO responseVO = new CheckTokenResponseVO();

		if(requestVO == null || CommonUtil.isNullOrBlank(requestVO.getToken())){
			responseVO.setCommonResult(new CommonResult(false,ZHBErrorConfig.getErrorInfo("600001")));
			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 =ZHBErrorConfig.getErrorInfo("810001");
		}else if(isTokenValid){
			String ticket = requestVO.getTicket();
			if(!CommonUtil.isNullOrBlank(ticket)){
				boolean valid = jwtTokenUtil.validateToken(token, ticket);
				if(!valid){
					success = false;
					message = ZHBErrorConfig.getErrorInfo("810001");
				}
			}
		}else{
			success = false;
			message = ZHBErrorConfig.getErrorInfo("810001");
		}
		responseVO.setCommonResult(new CommonResult(success,message));
		return responseVO;
	}
}
