/**
 * 
 */
package org.springblade.modules.auth.granter;

import javax.servlet.http.HttpServletRequest;

import org.springblade.common.unciom.UnicomUtil;
import org.springblade.core.secure.utils.WebUtil;
import org.springblade.core.tool.exception.ServiceException;
import org.springblade.modules.auth.enums.UserEnum;
import org.springblade.modules.auth.provider.ITokenGranter;
import org.springblade.modules.auth.provider.TokenParameter;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.entity.UserInfo;
import org.springblade.modules.system.service.IUserService;
import org.springframework.stereotype.Component;

import cn.hutool.core.lang.Tuple;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wookvn
 *
 *	联通短信登录
 */
@Slf4j
@Component
@AllArgsConstructor
public class UnicomSmsTokenGranter implements ITokenGranter {

	public static final String GRANT_TYPE = "unicomsms";
	
	private static final String SMS_VERCODE = "Sms-Code";
	private static final String SMS_USER_SIGN = "User-Sign";
	
	private final IUserService userService;
	
	@Override
	public UserInfo grant(TokenParameter tokenParameter) {
		HttpServletRequest request = WebUtil.getRequest();

		String verCode = request.getHeader(SMS_VERCODE);
		String userSign = request.getHeader(SMS_USER_SIGN);
		
		if (StrUtil.isBlank(userSign) || StrUtil.isBlank(verCode)) {
			throw new ServiceException("核心参数不能为空");
		}
		
		//解析用户ID
		Tuple userIdMobile = UnicomUtil.decryptAes(userSign);
		Long userId = userIdMobile.get(0);
		User user = userService.getById(userId);
		if(user == null || StrUtil.isEmpty(user.getPhone())) {
			throw new ServiceException("用户信息有误，请联系管理员");
		}
		
		//开始验证手机号验证码
		boolean ret = UnicomUtil.checkSmsCode(user.getPhone(), verCode);
		if(!ret) {
			throw new ServiceException("短信验证码错误");
		}
		
		// 获取用户类型
		String userType = tokenParameter.getArgs().getStr("userType");
		// 根据不同用户类型调用对应的接口返回数据，用户可自行拓展
		if (userType.equals(UserEnum.WEB.getName())) {
			return userService.userInfo(user, UserEnum.WEB);
		} else if (userType.equals(UserEnum.APP.getName())) {
			return userService.userInfo(user, UserEnum.APP);
		} else {
			return userService.userInfo(user, UserEnum.OTHER);
		}
	}

}
