package com.qmth.teachcloud.cas.util;

import com.qmth.teachcloud.cas.util.gdpu.CasUtils;
import com.qmth.teachcloud.cas.util.gdpu.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.util.Map;
import java.util.Objects;

/**
 * @Description: 广东药科大学cas工具类
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2023/6/12
 */
@Component
public class GdpuCasUtil {
    private static final Logger log = LoggerFactory.getLogger(GdpuCasUtil.class);

    @Resource
    AuthInfoService authInfoService;

    @Resource
    CommonCacheService commonCacheService;

    /**
     * 广东药科大学mq登录逻辑
     *
     * @param schoolCode
     * @param employeeNo
     * @return
     * @throws IOException
     */
    public RedirectParams mqAccount(String schoolCode, String employeeNo) {
        log.info("mqAccount schoolCode:{},employeeNo:{}", schoolCode, employeeNo);
        BasicSchool basicSchool = commonCacheService.schoolCache(schoolCode);
        Objects.requireNonNull(basicSchool, "学校信息不存在");

        String gdpuServiceAddress = null;
        Map<String, SimpleObject> mapSetting = commonCacheService.getSysSetting(basicSchool.getId());
        if (!CollectionUtils.isEmpty(mapSetting)) {
            SimpleObject simpleObject = mapSetting.get(Constants.GDPU_SERVICE_ADDRESS);
            Objects.requireNonNull(simpleObject, "未配置服务中台地址");
            gdpuServiceAddress = simpleObject.getValue();
            if (Objects.nonNull(gdpuServiceAddress) && !Objects.equals(gdpuServiceAddress.trim(), "")) {
                gdpuServiceAddress = gdpuServiceAddress.substring(0, gdpuServiceAddress.indexOf("/mq"));
            }
        }
        return new RedirectParams(employeeNo, schoolCode, gdpuServiceAddress, null);
    }

    /**
     * 广东药科大学登录逻辑
     *
     * @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("/"));
                }
                returnUrl = casAddress + Constants.SSO_LOGOUT_URI;
            }
        }
        AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();
        log.info("principal.getName():{}", principal.getName());
        log.info("principal.getAttributes():{}", JacksonUtil.parseJson(principal.getAttributes()));
        if (principal != null) {
            //获取用户信息中公开的Attributes部分
            Map<String, Object> map = principal.getAttributes();
            // 获取姓名,可以根据属性名称获取其他属性
            employeeNo = (String) map.get("username");
            String realname = (String) map.get("realname");
            log.info("employeeNo:{}", employeeNo);
            log.info("realname:{}", realname);
            log.info("schoolCode:{}", schoolCode);
            log.info("returnUrl:{}", returnUrl);
            openParams = new OpenParams(realname);
        }
        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;
    }
}
