package com.hotent.dataMiddlePlatform.manager.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.JsonNode;
import com.hotent.base.conf.JwtConfig;
import com.hotent.base.conf.SaaSConfig;
import com.hotent.base.conf.SsoConfig;
import com.hotent.base.feign.UCFeignService;
import com.hotent.base.jwt.JwtAuthenticationResponse;
import com.hotent.base.jwt.JwtTokenHandler;
import com.hotent.base.model.CommonResult;
import com.hotent.base.service.PwdStrategyService;
import com.hotent.base.util.*;
import com.hotent.baseInfo.manager.AuditedUnitManager;
import com.hotent.dataMiddlePlatform.manager.DataMiddlePlatformManager;
import com.hotent.uc.api.model.IUser;
import com.hotent.uc.manager.OrgManager;
import com.hotent.uc.manager.RoleManager;
import com.hotent.uc.manager.UserManager;
import com.hotent.uc.model.User;
import com.hotent.uc.params.org.OrgVo;
import com.hotent.uc.params.role.RoleVo;
import com.hotent.uc.params.user.UserVo;
import com.integration.oauth2.sdk.OAuth2Client;
import com.integration.oauth2.sdk.method.OAuth2ToMethod;
import com.integration.oauth2.sdk.model.Org;
import com.integration.oauth2.sdk.model.Role;
import com.integration.oauth2.sdk.model.UserDetail;
import com.integration.oauth2.sdk.model.UserInfo;
import com.integration.oauth2.sdk.response.AccessTokenResponse;
import oracle.net.ano.AuthenticationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 *@author: zhao yue yue
 *@create: 2025-11-06 11:37
 */
@Service
public class DataMiddlePlatformManagerImpl implements DataMiddlePlatformManager {


    private static final String baseUrl = "http://10.7.14.236:8280/stage-api/";
    private static final String clientId = "cbjsxt";
    private static final String clientSecret = "cbjsxt";
    private static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMnhQ99yP-eEU2jXdQWc6j-wWbqNLqOLinEGBY11WJUCmzHiEycDXPc6-3YMOvrdAiHZcjkMCzU_eRnBLUqkcNw9nhQrCak-sTpEVlAV21LskD6KMf-6PsfttUvpXeCO5g3Hg48F_vbLKxb8s_lcvQgCpKBIpsUdYRcp_PgSg8BQIDAQAB";
   /* private static final String code="前端传入";
    private static final String redirectUri="序号1的地址";*/

    @Autowired
    private OrgManager orgManager;

    @Autowired
    private UserManager userService;

    @Autowired
    JwtTokenHandler jwtTokenHandler;

    @Resource
    UserDetailsService userDetailsService;

    @Autowired
    JwtConfig jwtConfig;

    @Autowired
    SaaSConfig saasConfig;

    @Autowired
    UCFeignService uCFeignService;

    @Autowired
    RoleManager roleService;

    @Override
    public void sync() throws Exception {
        try {
            OAuth2Client oAuth2Client = OAuth2ToMethod.OAuth2Method.initClient( baseUrl,
                    clientId,
                    clientSecret,
                    publicKey
                    , 30);
            System.err.println("oAuth2Client:"+ JSON.toJSONString(oAuth2Client));
            String openApiToken = OAuth2ToMethod.getOpenApiToken("");
            System.err.println("openApiToken:"+ JSON.toJSONString(openApiToken));
            //1.拉去中台组织数据，2.组装组织数据，3.并批量添加
            List<Org> orgsAll = OAuth2ToMethod.getOrgsAll(openApiToken, "");
            List<OrgVo> orgVoList = orgsAll.stream().map(o -> {
                OrgVo orgVo = new OrgVo();
                BeanUtils.copyProperties(o,orgVo);
                return orgVo;
            }).collect(Collectors.toList());
            orgManager.addOrgs(orgVoList);
            //1.拉取中台用户数据，2.组装用户数据，3.批量添加
            int j=1;
            List<UserDetail> usersAll =new ArrayList<>();
            for (int i = 1; i==j ; i++) {
                usersAll = OAuth2ToMethod.getUsersAll(openApiToken, Integer.toString(i), "50");
                List<UserVo> userVos = usersAll.stream().map(u -> {
                    UserVo userVo = new UserVo();
                    BeanUtils.copyProperties(u,userVo);
                    userVo.setOrgId(u.getDeptId());
                    return userVo;
                }).collect(Collectors.toList());
                userService.addUsers(userVos);
                if (usersAll.size()==50) {
                    j++;
                }else {
                    j=1;
                }
            }

            //角色数据

            List<com.hotent.uc.model.Role> roleList = new ArrayList<>();
            for (int i = 1; i==j ; i++) {
                List<Role> roles = OAuth2ToMethod.getRolesAll(openApiToken, "1", "50");
                List<String> codes = roles.stream().map(Role::getCode).collect(Collectors.toList());
                List<com.hotent.uc.model.Role> ro=roleService.getRoles(codes);
                for (Role role : roles) {
                    com.hotent.uc.model.Role ored = ro.stream().filter(rol -> rol.getCode().equals(role.getCode())).findAny().orElse(null);
                    if (ored==null) {
                        com.hotent.uc.model.Role r = new com.hotent.uc.model.Role();
                        r.setId(UniqueIdUtil.getSuid());
                        r.setName(role.getName());
                        r.setCode(role.getCode());
                        r.setCreateTime(LocalDateTime.now());
                        roleList.add(r);
                    }
                }
                if (usersAll.size()==50) {
                    j++;
                }else {
                    j=1;
                }
            }
            roleService.saveBatch(roleList);


        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ResponseEntity<?> ssoDataMiddlePlatform(String code) throws Exception {
        OAuth2Client oAuth2Client = OAuth2ToMethod.OAuth2Method.initClient( baseUrl,
                clientId,
                clientSecret,
                publicKey
                , 30);
        AccessTokenResponse accessTokenWithCode = OAuth2ToMethod.getAccessTokenWithCode(code, "");
        System.err.println("免登录:"+JSON.toJSON(accessTokenWithCode));
        String accessToken = accessTokenWithCode.getValue().getAccess_token();
        UserInfo userInfo = OAuth2ToMethod.getUserInfo(accessToken);
        System.err.println("用户信息:"+JSON.toJSON(userInfo));
        CacheEvictUtil.deleteUserDetailsCache(userInfo.getName());
        // 当前切中的方法
        HttpServletRequest request = HttpUtil.getRequest();
        boolean isMobile = HttpUtil.isMobile(request);
        //final UserDetails userDetails = userDetailsService.loadUserByUsername("zhangming0030");
        final UserDetails userDetails = userDetailsService.loadUserByUsername(userInfo.getName());
        final String token = jwtTokenHandler.generateToken(userDetails);
        String userName = userDetails.getUsername();
        String account = "";
        String userId = "";
        Map<String, Object> userAttrs = new HashMap<String, Object>();
        if (userDetails instanceof IUser) {
            IUser user = ((IUser) userDetails);
            userName = user.getFullname();
            account = user.getAccount();
            userId = user.getUserId();
            request.setAttribute("loginUser", String.format("%s[%s]", userName, account));
            userAttrs.put("tenantId", user.getTenantId());
        }
        //获取超时时间
        //logger.debug("通过单点认证登录成功。");
        //处理单用户登录
        //if (!(code.isPresent() && SsoConfig.MODE_JWT.equals(mode))) {
            handleSingleLogin(isMobile, MapUtil.getString(userAttrs, "tenantId"), account, token);
        //}
        User byAccount = userService.getByAccount(userName);
        if (byAccount!=null) {
            userAttrs.put("dataScope",byAccount.getDataScope());
        }
        // Return the token
        return ResponseEntity.ok(new JwtAuthenticationResponse(token, userName, account, userId, jwtConfig.getExpirationLong(), userAttrs));

       /* User user = userService.getByAccount(userInfo.getName());
        CacheEvictUtil.deleteUserDetailsCache(user.getAccount());*/
        //return null;
    }


    /**
     * 处理单用户登录
     *
     * @param isMobile
     * @param username
     * @param token
     */
    private Map<String,Object> handleSingleLogin(boolean isMobile, String tenantId, String username, String token) {
        Map<String,Object> result=new HashMap<>();
        //如果是单用户登录
        if (jwtConfig.isSingle()) {
            String userAgent = isMobile ? "mobile" : "pc";
            // 非SaaS模式
            if (StringUtil.isEmpty(tenantId) && !saasConfig.isEnable()) {
                tenantId = "-1";
            }
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
            // 从缓存中获取token
            String oldToken = jwtTokenHandler.getTokenFromCache(userAgent, tenantId, username, jwtConfig.getExpiration());
            if(StringUtil.isNotEmpty(oldToken)) {
                if(jwtTokenHandler.validateToken(oldToken, userDetails) && !oldToken.equals(token)){
//                    throw new BaseException(ResponseErrorEnums.KICK_OFF_BY_ANOTHER);
                    System.out.println(username+":"+userAgent+"端重复登录了");
                    result.put("flag",true);
                    result.put("msg","当前账号已在另一地方登录，若不是本人操作，请注意账号安全");
                }
            }else{
                result.put("flag",false);
                result.put("msg","无多处登录");
            }
            // 以当前登录设备、租户ID、用户账号为key将token存放到缓存中
            jwtTokenHandler.putTokenInCache(userAgent, tenantId, username, jwtConfig.getExpiration(), token);
        }
        //处理用户登录日志
        uCFeignService.loginLog(username, isMobile ? "mobile" : "pc");
        return result;
    }

}
