package org.springblade.modules.auth.endpoint;

import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.wf.captcha.SpecCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.cache.CacheNames;
import org.springblade.core.cache.utils.CacheUtil;
import org.springblade.core.jwt.JwtUtil;
import org.springblade.core.jwt.props.JwtProperties;
import org.springblade.core.launch.constant.AppConstant;
import org.springblade.core.launch.constant.TokenConstant;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tenant.annotation.NonDS;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.WebUtil;
import org.springblade.modules.auth.provider.ITokenGranter;
import org.springblade.modules.auth.provider.TokenGranterBuilder;
import org.springblade.modules.auth.provider.TokenParameter;
import org.springblade.modules.auth.utils.TokenUtil;
import org.springblade.modules.desk.service.INoticeService;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.entity.UserInfo;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.UUID;

import static org.springblade.core.cache.constant.CacheConstant.*;

/**
 * 令牌端点
 *
 * @author Chill
 */
@NonDS
@ApiSort(1)
@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_AUTH_NAME)
@Api(value = "用户授权认证", tags = "授权接口")
public class BladeTokenEndPoint {

	private final BladeRedis bladeRedis;
	private final JwtProperties jwtProperties;
	private final IUserService userService;
	private final INoticeService noticeService;
	private final IDeptService deptService;

	@ApiLog("登录用户验证")
	@PostMapping("/oauth/token")
	@ApiOperation(value = "获取认证令牌", notes = "传入租户ID:tenantId,账号:account,密码:password")
	public Kv token(@ApiParam(value = "租户ID", required = true) @RequestParam String tenantId,
					@ApiParam(value = "账号", required = true) @RequestParam(required = false) String username,
					@ApiParam(value = "密码", required = true) @RequestParam(required = false) String password,
					@ApiParam(value = "sfzh", required = false) @RequestParam(required = false) String sfzh,
					@ApiIgnore @RequestHeader(name = TokenUtil.DEPT_HEADER_KEY, required = false) String deptId,
					@ApiIgnore @RequestHeader(name = TokenUtil.ROLE_HEADER_KEY, required = false) String roleId,
					@RequestParam(required = false) String code) {
		Kv authInfo = Kv.create();

		/*if (StringUtils.isNotBlank(code) && (!code.equals("486ca971e08526bed34c24d666e934d1") && !code.equals("204b60664d1afcba1360b04af00365fe") )) {
			// 先根据username查询code，如果code是空的，说明是第一次登录
			String userCode = userService.getCodeByUsername(username);
			if (StringUtils.isBlank(userCode)) {
				// 根据code查询username，如果username不是空的，说明是用别人的设备
				String account = userService.getUsernameByCode(code);
				if (StringUtils.isNotBlank(account)) {
					return authInfo.set("error_code", HttpServletResponse.SC_UNAUTHORIZED).set("error_description", "设备与账号不匹配，请联系管理员");
				} else {
					userService.updateCode(username, code);
				}
			} else if (!userCode.equals(code)) {
				// 不是第一次登录，用的是其他人的设备
				return authInfo.set("error_code", HttpServletResponse.SC_UNAUTHORIZED).set("error_description", "设备与账号不匹配，请联系管理员");
			}
		}*/

		// 互联网 禁止部分用户登录WEB
//		if (StringUtils.isBlank(code)) {
//			// 根据username查询角色名
//			String roleName = userService.getRoleName(username);
//			// 如果角色名
//			if (!roleName.contains("消防") && !roleName.contains("消救委") && !roleName.contains("超级管理员")) {
//				return authInfo.set("error_code", HttpServletResponse.SC_UNAUTHORIZED).set("error_description", "互联网禁止登录");
//			}
//		}

//		if (StringUtils.isNotBlank(code) && !code.equals("486ca971e08526bed34c24d666e934d1")) {
//			// 先根据username查询code，如果code是空的，说明是第一次登录
//			String userCode = userService.getCodeByUsername(username);
//			if (StringUtils.isBlank(userCode)) {
//				// 根据code查询username，如果username不是空的，说明是用别人的设备
//				String account = userService.getUsernameByCode(code);
//				if (StringUtils.isNotBlank(account)) {
//					return authInfo.set("error_code", HttpServletResponse.SC_UNAUTHORIZED).set("error_description", "设备与账号不匹配，请联系管理员");
//				} else {
//					userService.updateCode(username, code);
//				}
//			} else if (!userCode.equals(code)) {
//				// 不是第一次登录，用的是其他人的设备
//				return authInfo.set("error_code", HttpServletResponse.SC_UNAUTHORIZED).set("error_description", "设备与账号不匹配，请联系管理员");
//			}
//		}

		String grantType = WebUtil.getRequest().getParameter("grant_type");
		String refreshToken = WebUtil.getRequest().getParameter("refresh_token");

		String userType = Func.toStr(WebUtil.getRequest().getHeader(TokenUtil.USER_TYPE_HEADER_KEY), TokenUtil.DEFAULT_USER_TYPE);

		TokenParameter tokenParameter = new TokenParameter();
		tokenParameter.getArgs().set("tenantId", tenantId)
			.set("username", username)
			.set("password", password)
			.set("grantType", grantType)
			.set("refreshToken", refreshToken)
			.set("userType", userType)
			.set("deptId", deptId).set("roleId", roleId);

		ITokenGranter granter = TokenGranterBuilder.getGranter(grantType);
		UserInfo userInfo = granter.grant(tokenParameter);

		User user = userService.selectAccountByUserName(username);
		if (user != null){
			if (userInfo != null){
				userInfo.setZp(user.getZp());
			}
		} else {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", "用户未注册");
		}

		if (userInfo == null || userInfo.getUser() == null) {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", "用户名或密码不正确");
		}

		if (Func.isEmpty(userInfo.getRoles())) {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", "未获得用户的角色信息");
		}

		// 根据username查询角色名
		String roleName = userService.getRoleName(username);
		// 辅警禁止登录app
		if (roleName.contains("辅警")) {
			return authInfo.set("error_code", HttpServletResponse.SC_UNAUTHORIZED).set("error_description", "辅警禁止登录app");
		}

		if (userInfo.getUser().getRoleId().equals("1694608532769734657")){
			User fj = userService.selectMj(userInfo.getUser().getId());
			if (fj != null){
				userInfo.getUser().setMjname(fj.getMjname());
				userInfo.getUser().setSspcs(fj.getSspcs());
				userInfo.getUser().setMjId(fj.getMjId());
			}
		}
		if (!userInfo.getUser().getRoleId().equals("1123598816738675201") && !userInfo.getUser().getRoleId().equals("1725331085045587970") && !userInfo.getUser().getRoleId().equals("1780755525022023699")){
			User mj = userService.selectMjPcs(userInfo.getUser().getId());
			userInfo.getUser().setSspcs(mj.getSspcs());
		}

		// 获取dept_category 14=省厅 4=市局 5=分局 6=派出所 7=社区
		Dept deptCategory = deptService.getDeptCategoryByAccount(username);
		userInfo.setDeptCategory(deptCategory.getDeptCategory());
		userInfo.setAncestors(deptCategory.getAncestors());

//		userService.updateLastLoginTime(username);
		return TokenUtil.createAuthInfo(userInfo);
	}

	@ApiLog("登录用户验证")
	@PostMapping("/oauth/token2")
	@ApiOperation(value = "获取认证令牌", notes = "传入租户ID:tenantId,账号:account,密码:password")
	public Kv token2(@ApiParam(value = "租户ID", required = true) @RequestBody User user,
		@ApiIgnore @RequestHeader(name = TokenUtil.DEPT_HEADER_KEY, required = false) String deptId,
		@ApiIgnore @RequestHeader(name = TokenUtil.ROLE_HEADER_KEY, required = false) String roleId) {

		String code = user.getCode();
		String username = user.getUsername();
		String tenantId = "000000";
		String password = user.getPassword();
		Kv authInfo = Kv.create();

		if (StringUtils.isNotBlank(code)) {
			// 先根据username查询code，如果code是空的，说明是第一次登录
			String userCode = userService.getCodeByUsername(username);
			if (StringUtils.isBlank(userCode)) {
				// 根据code查询username，如果username不是空的，说明是用别人的设备
				String account = userService.getUsernameByCode(code);
				if (StringUtils.isNotBlank(account)) {
					return authInfo.set("error_code", HttpServletResponse.SC_UNAUTHORIZED).set("error_description", "设备与账号不匹配，请联系管理员");
				} else {
					userService.updateCode(username, code);
				}
			} else if (!userCode.equals(code)) {
				// 不是第一次登录，用的是其他人的设备
				return authInfo.set("error_code", HttpServletResponse.SC_UNAUTHORIZED).set("error_description", "设备与账号不匹配，请联系管理员");
			}
		}

		String grantType = user.getGrant_type();
		String refreshToken = user.getRefresh_token();

		String userType = Func.toStr(WebUtil.getRequest().getHeader(TokenUtil.USER_TYPE_HEADER_KEY), TokenUtil.DEFAULT_USER_TYPE);

		TokenParameter tokenParameter = new TokenParameter();
		tokenParameter.getArgs().set("tenantId", tenantId)
			.set("username", username)
			.set("password", password)
			.set("grantType", grantType)
			.set("refreshToken", refreshToken)
			.set("userType", userType)
			.set("deptId", deptId).set("roleId", roleId);

		ITokenGranter granter = TokenGranterBuilder.getGranter(grantType);
		UserInfo userInfo = granter.grant(tokenParameter);

		if (userInfo == null || userInfo.getUser() == null) {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", "用户名或密码不正确");
		}

		if (Func.isEmpty(userInfo.getRoles())) {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", "未获得用户的角色信息");
		}

		userService.updateLastLoginTime(username);
		return TokenUtil.createAuthInfo(userInfo);
	}

	@ApiLog("登录用户验证")
	@PostMapping("/oauth/token3")
	@ApiOperation(value = "获取认证令牌", notes = "传入租户ID:tenantId,账号:account,密码:password")
	public Kv token3(@ApiParam(value = "租户ID", required = true) @RequestBody String username, @RequestBody String password) {

		//String username = user.getUsername();
		String tenantId = "000000";
		//String password = "e10adc3949ba59abbe56e057f20f883e";
		Kv authInfo = Kv.create();

		String grantType = WebUtil.getRequest().getParameter("grant_type");
		String refreshToken = WebUtil.getRequest().getParameter("refresh_token");

		//String grantType = user.getGrant_type();
		//String refreshToken = user.getRefresh_token();

		String userType = Func.toStr(WebUtil.getRequest().getHeader(TokenUtil.USER_TYPE_HEADER_KEY), TokenUtil.DEFAULT_USER_TYPE);

		TokenParameter tokenParameter = new TokenParameter();
		tokenParameter.getArgs().set("tenantId", tenantId)
			.set("username", username)
			.set("password", password)
			.set("grantType", grantType)
			.set("refreshToken", refreshToken)
			.set("userType", userType);

		ITokenGranter granter = TokenGranterBuilder.getGranter(grantType);
		UserInfo userInfo = granter.grant(tokenParameter);

		if (userInfo == null || userInfo.getUser() == null) {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", "用户名或密码不正确");
		}

		if (Func.isEmpty(userInfo.getRoles())) {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", "未获得用户的角色信息");
		}
		Dept deptCategory = deptService.getDeptCategoryByAccount(username);
		userInfo.setDeptCategory(deptCategory.getDeptCategory());
		userInfo.setAncestors(deptCategory.getAncestors());
		userService.updateLastLoginTime(username);
		return TokenUtil.createAuthInfo(userInfo);
	}

	@GetMapping("/oauth/logout")
	@ApiOperation(value = "退出登录")
	public Kv logout() {
		BladeUser user = AuthUtil.getUser();
		if (user != null && jwtProperties.getState()) {
			String token = JwtUtil.getToken(WebUtil.getRequest().getHeader(TokenConstant.HEADER));
			JwtUtil.removeAccessToken(user.getTenantId(), String.valueOf(user.getUserId()), token);
		}
		return Kv.create().set("success", "true").set("msg", "success");
	}

	@GetMapping("/oauth/captcha")
	@ApiOperation(value = "获取验证码")
	public Kv captcha() {
		SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
		String verCode = specCaptcha.text().toLowerCase();
		String key = UUID.randomUUID().toString();
		// 存入redis并设置过期时间为30分钟
		bladeRedis.setEx(CacheNames.CAPTCHA_KEY + key, verCode, Duration.ofMinutes(30));
		// 将key和base64返回给前端
		return Kv.create().set("key", key).set("image", specCaptcha.toBase64());
	}

	@GetMapping("/oauth/clear-cache")
	@ApiOperation(value = "清除缓存")
	public Kv clearCache() {
		CacheUtil.clear(BIZ_CACHE);
		CacheUtil.clear(USER_CACHE);
		CacheUtil.clear(DICT_CACHE);
		CacheUtil.clear(FLOW_CACHE);
		CacheUtil.clear(SYS_CACHE);
		CacheUtil.clear(PARAM_CACHE);
		CacheUtil.clear(RESOURCE_CACHE);
		CacheUtil.clear(MENU_CACHE);
		CacheUtil.clear(DICT_CACHE, Boolean.FALSE);
		CacheUtil.clear(MENU_CACHE, Boolean.FALSE);
		CacheUtil.clear(SYS_CACHE, Boolean.FALSE);
		CacheUtil.clear(PARAM_CACHE, Boolean.FALSE);
		return Kv.create().set("success", "true").set("msg", "success");
	}
}
