package com.qmth.teachcloud.cas.util;

import com.qmth.teachcloud.cas.util.bjwlxy.CasUtils;
import com.qmth.teachcloud.cas.util.bjwlxy.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.HttpUtil;
import com.qmth.teachcloud.exchange.common.util.ServletUtil;
import net.psctech.sso.filter.LoginFilter;
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.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: 陕西宝鸡文理学院cas工具类
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2023/6/12
 */
@Component
public class BjwlxyCasUtil {
    private static final Logger log = LoggerFactory.getLogger(BjwlxyCasUtil.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, casAddress = null, schoolServiceAddress = null;
        Map<String, SimpleObject> mapSetting = commonCacheService.getSysSetting(basicSchool.getId());
        if (!CollectionUtils.isEmpty(mapSetting)) {
            SimpleObject simpleObject = mapSetting.get(SystemConstant.CAS_ADDRESS);
            Objects.requireNonNull(simpleObject, "未配置单点登录地址");
            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;
            }
            simpleObject = mapSetting.get(SystemConstant.SCHOOL_SERVICE_ADDRESS);
            schoolServiceAddress = simpleObject.getValue();
            if (Objects.nonNull(schoolServiceAddress) && !Objects.equals(schoolServiceAddress.trim(), "")) {
                if (schoolServiceAddress.lastIndexOf("/") == schoolServiceAddress.length() - 1) {
                    schoolServiceAddress = schoolServiceAddress.substring(0, schoolServiceAddress.lastIndexOf("/"));
                }
            }
        }

        String tkt = request.getParameter("ticket");
        log.info("tkt:{}", tkt);
        if (Objects.isNull(tkt) || tkt.length() == 0) {
            employeeNo = SystemConstant.getNanoId();
            returnUrl = schoolServiceAddress + Constants.CAS_LOGIN_URL + SystemConstant.GET_UNKNOWN + SystemConstant.SERVICE_KEY + SystemConstant.GET_EQUAL + casAddress + Constants.SSO_LOGIN_URI;
        } else {//校验ticket，获取用户信息
            String validateurl = schoolServiceAddress + Constants.CAS_SERVICE_VALID_DATE_URL + SystemConstant.GET_UNKNOWN + "ticket=" + tkt + SystemConstant.GET_SYMBOL + SystemConstant.SERVICE_KEY + SystemConstant.GET_EQUAL + casAddress + Constants.SSO_LOGIN_URI;
            log.info("-------validateurl-----{}", validateurl);
            //发送请求
//            String data = ResponseWithHttpClient.getResponseWithHttpClient(validateurl, SystemConstant.CHARSET_NAME);
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("ticket", tkt);
            map.put(SystemConstant.SERVICE_KEY, casAddress + Constants.SSO_LOGIN_URI);
            String data = HttpUtil.get(schoolServiceAddress + Constants.CAS_SERVICE_VALID_DATE_URL, map, null, System.currentTimeMillis());
            log.info("data:{}", data);
            if (Objects.nonNull(data)) {
                String username = null;
                Pattern pt = Pattern.compile("<cas:user>(.*)</cas:user>");
                Matcher match = pt.matcher(data);
                while (match.find()) {
                    username = match.group(1);
                }
                if (Objects.nonNull(username)) {
                    employeeNo = username;
                    openParams = new OpenParams(username);
                }
            }
        }
        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("/"));
                }
            }
            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("/"));
                }
            }
            log.info("cas:logout:logoutUrl:{}", CasUtils.getLogoutUrl(schoolServiceAddress, casAddress));
            //跳转至注销后地址
            response.setHeader(SystemConstant.ACCESS_CONTROL_ALLOW_ORIGIN, SystemConstant.PATH_MATCH);
            response.sendRedirect(CasUtils.getLogoutUrl(schoolServiceAddress, casAddress));
        }
    }

    /**
     * 知学登录
     *
     * @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;
    }
}
