package com.yunfeiyun.agmp.common.core.domain.model;

import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap;
import com.yunfeiyun.agmp.common.constant.ErrorCode;
import com.yunfeiyun.agmp.common.core.domain.AjaxResult;
import com.yunfeiyun.agmp.common.framework.web.service.PortalService;
import com.yunfeiyun.agmp.common.framework.web.service.TokenService;
import com.yunfeiyun.agmp.common.utils.spring.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

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

@Component
public class SessionJoinCache {

    private static final Logger log = LoggerFactory.getLogger(SessionJoinCache.class);
    public static Map<String, ReentrantLockList<LinkSession>> sessionMap = (Map<String, ReentrantLockList<LinkSession>>)(new ConcurrentLinkedHashMap.Builder()).maximumWeightedCapacity(100000L).build();

    @Autowired
    RestTemplate restTemplate;

    public static boolean containSession(String ssoTokenKey,String sessionToken){
        ReentrantLockList<LinkSession> set = sessionMap.get(ssoTokenKey);
        for(int pos = 0; pos < set.getSize();pos++){
            if(sessionToken.equals(set.get(pos).getToken())){
                return true;
            }
        }
        return false;
    }

    public static synchronized LinkSession createSession(String sysId, String ssoTokenKey,String sessionToken,String logoutUr){
        //销毁全局Token
        ssoTokenKey = ssoTokenKey.indexOf("PTS_login_tokens:") > -1 ? ssoTokenKey.substring("PTS_login_tokens:".length()) : ssoTokenKey;
        ReentrantLockList<LinkSession> set = sessionMap.get(ssoTokenKey);
        if (set == null) {
            set = new ReentrantLockList<>();
            sessionMap.put(ssoTokenKey, set);
        }
        LinkSession session = null;
        if (!containSession(ssoTokenKey,sessionToken)) {
            session = new LinkSession(sessionToken);
            session.setSysId( sysId );
            session.setLogoutUrl( logoutUr );
            sessionMap.get(ssoTokenKey).add(session);
        }
        log.info("主会话Id={}" , ssoTokenKey);
        ReentrantLockList<LinkSession> newSet = sessionMap.get(ssoTokenKey);
        for(int pos = 0; pos < newSet.getSize();pos++){
            //if(sessionToken.equals(newSet.get(pos).getToken())){
            log.info("子会话Id={}" , newSet.get(pos).toString());
            //}
        }
        return session;
    }


    public static synchronized LinkSession destroySession(String ssoToken){
        //拿token得到KEY
        String ssoTokenKey = ssoToken;
        ssoTokenKey = ssoTokenKey.indexOf("PTS_login_tokens:") > -1 ? ssoTokenKey.substring("PTS_login_tokens:".length()) : ssoTokenKey;

        ReentrantLockList<LinkSession> newSet = sessionMap.get(ssoTokenKey);
        //销毁全局Token
        SpringUtils.getBean(TokenService.class).delLoginUser(ssoTokenKey);

        if(newSet == null ) {
            log.warn("销毁会话={} 子系统上线为空 "  , ssoTokenKey);
            return null;
        }
        for(int pos = 0; pos < newSet.getSize();pos++){
            LinkSession session = newSet.get(pos);
            HashMap<String, String> params = new HashMap<>();
            params.put("sysToken", session.getToken());
            params.put("sysName", session.getSysId());
            params.put("sysId", session.getSysId());
            try {

                log.warn("销毁会话={} 待销毁sysToken={} "  , ssoTokenKey, session.toString() );
                //sessionMap.get(ssoTokenKey).remove(newSet.get(pos));
                SpringUtils.getBean(RestTemplate.class).postForObject(session.getLogoutUrl(), params, AjaxResult.class );
            }catch (Exception e){

            }
        }
        if (newSet.getSize() == 0) {
            sessionMap.remove(ssoTokenKey);
        }

        return null;
    }


    public static AjaxResult registerSession(PtsTokenKey ptsTokenKey){
        HashMap<String, String> params = new HashMap<>();
        if(ptsTokenKey ==null || ptsTokenKey.getPtsToken() == null || !StringUtils.hasText(ptsTokenKey.getPtsToken())){
            return   AjaxResult.error(ErrorCode.AUTH_SSO.getCode());
        }
        PortalInfo portalInfo = SpringUtils.getBean(PortalService.class).getSsoInfo();
        params.put("ptsToken", ptsTokenKey.getPtsToken());
        params.put("sysToken", ptsTokenKey.getSysToken());
        params.put("logoutUrl" , portalInfo.getAppLogoutUrl());
        params.put("sysId", ptsTokenKey.getSysName());
        AjaxResult response = null;
        try {
            response = SpringUtils.getBean(RestTemplate.class).postForObject(portalInfo.getSsoSessionUrl(), params, AjaxResult.class );
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(ErrorCode.AUTH_SSO.getCode());
        }
        return null;
    }

}
