package com.persagy.proxy.common.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.persagy.dmp.auth.client.EmsSaasWebClient;
import com.persagy.dmp.auth.domain.Group;
import com.persagy.dmp.auth.domain.Project;
import com.persagy.dmp.auth.domain.ResultReturn;
import com.persagy.dmp.auth.service.impl.AbstractAuthServiceImpl;
import com.persagy.dmp.common.constant.CommonConstant;
import com.persagy.dmp.common.constant.ResponseCode;
import com.persagy.dmp.common.context.AppContext;
import com.persagy.dmp.common.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 运维平台2.0 鉴权实现类
 * 从head中获取上下文信息，并校验集团、项目是否有效
 * @author Charlie Yu
 * @date 2021-11-02
 */
@Deprecated
public class EmsAuthServiceImpl extends AbstractAuthServiceImpl {
    @Autowired
    private EmsSaasWebClient emsSaasWebClient;

    @Override
    public void loginSuccess(HttpServletRequest request, HttpServletResponse response) {
        super.loginSuccess(request, response);
        loadContextByRequest(request);
        if (StrUtil.isBlank(AppContext.getContext().getGroupCode())
                && StrUtil.isBlank(AppContext.getContext().getProjectId())){
            // 两者都为空时不做校验
            return;
        }
        //
        JSONObject param = new JSONObject();
        if (StrUtil.isNotBlank(AppContext.getContext().getProjectId())){
            param.put(CommonConstant.QUERY_PROJECTIDS,CollUtil.newArrayList(AppContext.getContext().getProjectId()));
        }
        ResultReturn<Group> queryResult = emsSaasWebClient.queryGroupProjectList(param);
        if (!CommonConstant.QUERY_SUCCESS.equals(queryResult.getResult())){
            throw new BusinessException(queryResult.getResultMsg());
        }
        List<Group> content = queryResult.getContent();
        if (CollUtil.isEmpty(content)){
            throw new BusinessException(ResponseCode.A0402.getCode(), ResponseCode.A0402.getDesc());
        }
        Map<String, List<Project>> groupMap = content.stream()
                .collect(Collectors.toMap(Group::getGroupCode, Group::getProjects, (k1, k2) -> k1));
        // 1.没有集团编码时根据项目匹配集团
        // 如果集团编码为空则通过项目id查找
        Set<Map.Entry<String, List<Project>>> entries = groupMap.entrySet();
        flag:
        for (Map.Entry<String, List<Project>> entry : entries) {
            if (CollUtil.isEmpty(entry.getValue())){
                continue;
            }
            for (Project project : entry.getValue()) {
                if (AppContext.getContext().getProjectId().equals(project.getProjectId())){
                    AppContext.getContext().setGroupCode(entry.getKey());
                    break flag;
                }
            }
        }
        // 2.验证集团是否有效
        if (StrUtil.isBlank(AppContext.getContext().getGroupCode())
                || !groupMap.containsKey(AppContext.getContext().getGroupCode())){
            throw new BusinessException(ResponseCode.A0402.getCode(), ResponseCode.A0402.getDesc());
        }
    }

    @Override
    protected void loadContextByRequest(HttpServletRequest request) {
        AppContext context = AppContext.getContext();
        context.setGroupCode(request.getHeader("groupCode"));
        context.setProjectId(request.getHeader("projectId"));
        context.setAppId(request.getHeader("appId"));
        String userId = request.getHeader("userId");
        // 无用户时，默认为默认系统用户
        if(StrUtil.isBlank(userId)) {
            context.setAccountId(CommonConstant.DEFAULT_ID);
        }
        // 无项目id时,尝试从请求URL中获取
        if (StrUtil.isBlank(request.getHeader("projectId"))
                && StrUtil.isNotBlank(request.getParameter(CommonConstant.QUERY_PROJECTID))){
            context.setProjectId(request.getParameter(CommonConstant.QUERY_PROJECTID));
        }
    }
}
