package org.security.auth.endpoint;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.security.system.user.feign.IUserClient;
import org.security.system.user.vo.UserVO;
import org.springblade.core.launch.constant.TokenConstant;
import org.springblade.core.secure.TokenInfo;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tenant.annotation.NonDS;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author zj 2022/9/5
 */
@NonDS
@Slf4j
@RestController
@AllArgsConstructor
public class AuthEndPoint {
	private final IUserClient iUserClient;

	/**
	 * app用户验证生成token
	 *
	 * @param code 工号
	 * @return
	 */
	@GetMapping("/app/auth")
	public R appAuth(String code) {
		R<UserVO> userResult = iUserClient.getUserByCode(code);
		UserVO userVO = userResult.getData();
		if (!userResult.isSuccess() || Objects.isNull(userVO)) {
			return R.fail("用户未在安防系统注册");
		}
		TokenInfo jwt = SecureUtil.createJWT(getAppTokenMap(userVO), "app", "security", "access_token");
		HashMap<String, String> res = new HashMap<>();
		res.put("code", userVO.getCode());
		res.put("userName", userVO.getRealName());
		res.put("token", jwt.getToken());
		return R.data(res);
	}

	private Map<String, Object> getAppTokenMap(UserVO userVO) {
		Map<String, Object> info = new HashMap<>(16);
		info.put(TokenConstant.CLIENT_ID, "app");
		info.put(TokenConstant.USER_ID, Func.toStr(userVO.getId()));
		info.put(TokenConstant.DEPT_ID, Func.toStr(userVO.getDeptId()));
		info.put(TokenConstant.POST_ID, Func.toStr(userVO.getPostId()));
		info.put(TokenConstant.ROLE_ID, Func.toStr(userVO.getRoleId()));
		info.put(TokenConstant.TENANT_ID, userVO.getTenantId());
		info.put(TokenConstant.OAUTH_ID, "");
		info.put(TokenConstant.ACCOUNT, userVO.getAccount());
		info.put(TokenConstant.USER_NAME, userVO.getRealName());
		info.put(TokenConstant.NICK_NAME, userVO.getName());
		info.put(TokenConstant.REAL_NAME, userVO.getRealName());
		info.put(TokenConstant.ROLE_NAME, userVO.getRoleName());
		info.put(TokenConstant.AVATAR, userVO.getAvatar());
		info.put(TokenConstant.DETAIL, "web");
		info.put(TokenConstant.LICENSE, "security");
		return info;
	}
}
