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.utils.FeignUtil;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.LoginInfoModel;
import com.yeejoin.amos.openapi.enums.SSOLoginStatusEnum;
import com.yeejoin.amos.openapi.enums.TaAccessConfigBizeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import java.util.Date;
import java.util.List;
import java.util.Map;

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

	@Autowired
	private SSOAccountRelationServiceImpl ssoAccountRelationService;

	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();
		if (ValidationUtil.isEmpty(ssoAccountRelation)) {
			// 如果用户不存在，则创建用户
			ssoAccountRelation = new SSOAccountRelation();
			ssoAccountRelation.setPortalUserId(userId);
			ssoAccountRelation.setPortalUserPhone(userPhoneNumber);
			ssoAccountRelation.setLoginStatus(SSOLoginStatusEnum.FAILED.getCode());
			ssoAccountRelation.setCreateDate(new Date());
			ssoAccountRelationService.save(ssoAccountRelation);
			return null;
		}
		// 存在两个平台用户对应关系并且登录状态(LoginStatus)为1，则用查到的用户信息登录监管平台
		if (ssoAccountRelation.getLoginStatus().equals(SSOLoginStatusEnum.SUCCESS.getCode())) {
			// 1.查询监管平台用户登录信息（loginId和password）
			List<LoginInfoModel> agencyUserClientList = FeignUtil.remoteCall(() -> Privilege.agencyUserClient.getLoginInfoList(userPhoneNumber));
			if (ValidationUtil.isEmpty(agencyUserClientList)) {
				ssoAccountRelation.setLoginStatus(SSOLoginStatusEnum.FAILED.getCode());
				ssoAccountRelationService.updateById(ssoAccountRelation);
				return null;
			}
			// 2.登录监管平台
			// 3.为用户授权应用
			// 4.返回监管平台用户登录信息
		}
		return null;
	}

	/**
	 * 获取统一门户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;
	}
}
