package com.qmth.teachcloud.cas.util;

import com.qmth.teachcloud.cas.util.sxmu.CasUtils;
import com.qmth.teachcloud.cas.util.sxmu.Constants;
import com.qmth.teachcloud.exchange.common.bean.dto.syssetting.SimpleObject;
import com.qmth.teachcloud.exchange.common.bean.params.OpenParams;
import com.qmth.teachcloud.exchange.common.bean.params.RedirectParams;
import com.qmth.teachcloud.exchange.common.contant.SystemConstant;
import com.qmth.teachcloud.exchange.common.entity.BasicSchool;
import com.qmth.teachcloud.exchange.common.service.AuthInfoService;
import com.qmth.teachcloud.exchange.common.service.CommonCacheService;
import com.qmth.teachcloud.exchange.common.util.JacksonUtil;
import com.qmth.teachcloud.exchange.common.util.ServletUtil;
import net.psctech.sso.filter.LoginFilter;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.Principal;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: 山西医科大学cas工具类
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2024/3/25
 */
@Component
public class SxmuCasUtil {
    private static final Logger log = LoggerFactory.getLogger(SxmuCasUtil.class);

    @Resource
    AuthInfoService authInfoService;

    @Resource
    CommonCacheService commonCacheService;

    /**
     * 山西医科大学登录逻辑
     *
     * @param schoolCode
     * @return
     * @throws IOException
     */
    public RedirectParams authentication(String schoolCode) throws IOException {
        HttpServletRequest request = ServletUtil.getRequest();
        authInfoService.appHasExpired(schoolCode);

        BasicSchool basicSchool = commonCacheService.schoolCache(schoolCode);
        Objects.requireNonNull(basicSchool, "学校信息不存在");

        OpenParams openParams = null;
        String employeeNo = null, returnUrl = null;
        Map<String, SimpleObject> mapSetting = commonCacheService.getSysSetting(basicSchool.getId());
        if (!CollectionUtils.isEmpty(mapSetting)) {
            SimpleObject simpleObject = mapSetting.get(SystemConstant.CAS_ADDRESS);
            Objects.requireNonNull(simpleObject, "未配置单点登录地址");
            String casAddress = simpleObject.getValue();
            if (Objects.nonNull(casAddress) && !Objects.equals(casAddress.trim(), "")) {
                if (casAddress.lastIndexOf("/") == casAddress.length() - 1) {
                    casAddress = casAddress.substring(0, casAddress.lastIndexOf("/"));
                }
                String logoutUri = Constants.SSO_LOGOUT_URI;
                logoutUri = logoutUri.replace(SystemConstant.SCHOOL_CODE, schoolCode);
                returnUrl = casAddress + logoutUri;
            }
        }
        String uid = request.getRemoteUser();
        log.info("uid:{}", uid);
        String cn = "";
        Principal principal = request.getUserPrincipal();
        if (principal != null && principal instanceof AttributePrincipal) {
            AttributePrincipal aPrincipal = (AttributePrincipal) principal;
            //获取用户信息中公开的Attributes部分
            Map<String, Object> map = aPrincipal.getAttributes();
            log.info("principal map:{}", JacksonUtil.parseJson(map));
            // 获取姓名,可以根据属性名称获取其他属性
            cn = (String) map.get("cn");
            employeeNo = uid;
            openParams = new OpenParams(cn);
        }
        return new RedirectParams(employeeNo, schoolCode, returnUrl, openParams);
    }

    /**
     * 山西医科大学注销逻辑
     *
     * @param schoolCode
     * @throws IOException
     */
    public void logout(String schoolCode) throws IOException {
        HttpServletResponse response = ServletUtil.getResponse();
        HttpSession session = ServletUtil.getSession();
        authInfoService.appHasExpired(schoolCode);
        //注销本系统session
        session.invalidate();

        BasicSchool basicSchool = commonCacheService.schoolCache(schoolCode);
        Objects.requireNonNull(basicSchool, "学校信息不存在");

        Map<String, SimpleObject> mapSetting = commonCacheService.getSysSetting(basicSchool.getId());
        if (!CollectionUtils.isEmpty(mapSetting)) {
            SimpleObject simpleObject = mapSetting.get(SystemConstant.SCHOOL_SERVICE_ADDRESS);
            Objects.requireNonNull(simpleObject, "未配置学校cas地址");
            String schoolServiceAddress = simpleObject.getValue();
            if (Objects.nonNull(schoolServiceAddress) && !Objects.equals(schoolServiceAddress.trim(), "")) {
                if (schoolServiceAddress.lastIndexOf("/") == schoolServiceAddress.length() - 1) {
                    schoolServiceAddress = schoolServiceAddress.substring(0, schoolServiceAddress.lastIndexOf("/"));
                }
            }
            log.info("cas:logout:logoutUrl:{}", CasUtils.getLogoutUrl(schoolServiceAddress));
            //跳转至注销后地址
            response.setHeader(SystemConstant.ACCESS_CONTROL_ALLOW_ORIGIN, SystemConstant.PATH_MATCH);
            response.sendRedirect(CasUtils.getLogoutUrl(schoolServiceAddress));
        }
    }

    /**
     * 知学登录
     *
     * @param schoolCode
     * @return
     * @throws IOException
     */
    public RedirectParams zxzkLogin(String schoolCode) throws IOException {
        String logoutUrl = null;
        HttpSession session = ServletUtil.getSession();
        String userName = "";
        Object object = session.getAttribute(LoginFilter.CONST_CAS_USERNAME);
        RedirectParams redirectParams = null;
        if (object != null) {
            userName = object.toString();
            redirectParams = new RedirectParams(userName, schoolCode, logoutUrl, null);
        }
        return redirectParams;
    }
}
