package com.yeejoin.amos.api.openapi.face.service;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.api.openapi.face.orm.entity.SSOAccountRelation;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.component.feign.model.Page;
import com.yeejoin.amos.component.feign.utils.FeignUtil;
import com.yeejoin.amos.component.robot.AmosRequestContext;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.VerifyCodeAuthModel;
import com.yeejoin.amos.feign.privilege.util.AesUtil;
import com.yeejoin.amos.openapi.enums.SSOLoginStatusEnum;
import com.yeejoin.amos.openapi.enums.TaAccessConfigBizeEnum;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 统一门户sso 服务实现类
 *
 * @author tb
 * @date 2024-12-31
 */
@Service
public class SSOServiceImpl  {

	private static final Logger logger = LogManager.getLogger(SSOServiceImpl.class);

	@Autowired
	private SSOAccountRelationServiceImpl ssoAccountRelationService;

	@Autowired
	AmosRequestContext amosRequestContext;

	public final String ERROR_MESSAGE = "读取服务配置异常";

	public Map<String, String> getPlatformUserInfo(String portalCode) {
		// 获取统一门户accessToken
		String accessToken = getPortalAccessToken(portalCode);
		if (ValidationUtil.isEmpty(accessToken)) {
			return null;
		}
		// 获取统一门户用户信息
		JSONObject userInfo = getPortalUserInfo(accessToken);
		if (ValidationUtil.isEmpty(userInfo)) {
			return null;
		}
		String userPhoneNumber = userInfo.getString("phone_number");
		String userId = userInfo.getString("id");
		SSOAccountRelation ssoAccountRelation = ssoAccountRelationService.lambdaQuery().eq(SSOAccountRelation::getPortalUserId, userId).one();
		RequestContext.setProduct(amosRequestContext.getProduct());
		RequestContext.setAppKey(amosRequestContext.getAppKey());
		RequestContext.setToken(amosRequestContext.getToken());
		// 1.查询监管平台用户信息
		Page<AgencyUserModel> agencyUserModelList = FeignUtil.remoteCall(() -> Privilege.agencyUserClient.queryForPage(null, null, userPhoneNumber, null, 1, 100));
		if (ValidationUtil.isEmpty(agencyUserModelList) || agencyUserModelList.getTotal() == 0) {
			if (ValidationUtil.isEmpty(ssoAccountRelation)) {
				// 如果绑定用户关系不存在，则创建
				ssoAccountRelation = new SSOAccountRelation();
				ssoAccountRelation.setPortalUserId(userId);
				ssoAccountRelation.setPortalUserPhone(userPhoneNumber);
				ssoAccountRelation.setCreateDate(new Date());
			}
			ssoAccountRelation.setLoginStatus(SSOLoginStatusEnum.FAILED.getCode());
			ssoAccountRelationService.saveOrUpdate(ssoAccountRelation);
			return null;
		}  else {
			if (ValidationUtil.isEmpty(ssoAccountRelation)) {
				// 如果绑定用户关系不存在，则创建
				ssoAccountRelation = new SSOAccountRelation();
				ssoAccountRelation.setPortalUserId(userId);
				ssoAccountRelation.setPortalUserPhone(userPhoneNumber);
				ssoAccountRelation.setCreateDate(new Date());
			}
			ssoAccountRelation.setLoginStatus(SSOLoginStatusEnum.SUCCESS.getCode());
			// 2.登录监管平台
			Map<String, String> agencyUserModel = (Map<String, String>) agencyUserModelList.getRecords().get(0);
			VerifyCodeAuthModel verifyCodeAuthModel = new VerifyCodeAuthModel();
			verifyCodeAuthModel.setLoginId(agencyUserModel.get("userName"));
			verifyCodeAuthModel.setVerifyCode(AesUtil.encode(agencyUserModel.get("userName"),"qaz"));
			FeignClientResult<Map<String, String>> loginResult;
			loginResult = Privilege.authClient.userNameVerifyCode(verifyCodeAuthModel);
			if (loginResult.getStatus() != 200) {
				return null;
			}
			ssoAccountRelationService.saveOrUpdate(ssoAccountRelation);
			String amosUserId = loginResult.getResult().get("userId");
			String amosToken = loginResult.getResult().get("token");
			// 3.为用户授权应用
			RequestContext.setToken(amosToken);
			RequestContext.setAgencyCode("tzs");
			RequestContext.setExeUserId(amosUserId);
			FeignUtil.remoteCall(() -> Privilege.applicationClient.queryUserService());
			// 4.返回监管平台用户登录信息
			Map<String, String> result = new HashMap<>();
			result.put("amosToken", amosToken);
			result.put("amosUserId", amosUserId);
			return result;
		}
	}

	/**
	 * 获取统一门户accessToken
	 *
	 * @param portalCode
	 * @return
	 */
	private String getPortalAccessToken(String portalCode) {
		Map<String, String> configMap = TaAccessConfigServiceImpl.configMap.get(TaAccessConfigBizeEnum.SSO.getAttribute());
		String apiServerUrl = configMap.get("apiServer");
		String clientId = configMap.get("clientId");
		String clientSecret = configMap.get("clientSecret");
		String accessTokenUrlTemplate = configMap.get("accessTokenUrl");
		String redirectUrl = configMap.get("redirectUrl");
		String accessTokenUrl = String.format(accessTokenUrlTemplate, clientId, clientSecret, portalCode, URLUtil.encode(redirectUrl));

		String response = HttpUtil.get(URLUtil.completeUrl(apiServerUrl, accessTokenUrl));
		JSONObject res = JSONObject.parseObject(response);
		return res.getString("access_token");
	}

	/**
	 * 获取统一门户用户信息
	 *
	 * @param accessToken
	 * @return
	 */
	private JSONObject getPortalUserInfo(String accessToken) {
		Map<String, String> configMap = TaAccessConfigServiceImpl.configMap.get(TaAccessConfigBizeEnum.SSO.getAttribute());
		String apiServerUrl = configMap.get("apiServer");
		String userInfoUrlTemplate = configMap.get("userInfoUrl");
		String userInfoUrl = String.format(userInfoUrlTemplate, accessToken);
		String response = HttpUtil.get(URLUtil.completeUrl(apiServerUrl, userInfoUrl));
		JSONObject res = JSONObject.parseObject(response);
		if (ValidationUtil.isEmpty(res) || ValidationUtil.isEmpty(res.get("phone_number"))) {
			return null;
		}
		return res;
	}
}
