package com.fastbee.framework.interceptor;



import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.fastbee.common.holder.ProjectHolder;
import com.fastbee.common.holder.ProjectInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.annotation.Nullable;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Objects;



/**
 * @author mijiupro
 */

@Component
@Slf4j
public class ProjectDataIsolationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {

        log.info("进入项目数据隔离拦截器");
        //放行预检请求
        if ("OPTIONS".equalsIgnoreCase(Objects.requireNonNull(request.getMethod()))) {
            return true;
        }
        if ("DELETE".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
//        if ("POST".equalsIgnoreCase(request.getMethod())) {
//                return true;
//            }
        if ("PUT".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        //当前项目信息
        ProjectInfo projectInfo = ProjectInfo.builder()
                .projectId("")
                .projectIdList(new ArrayList<>())
                .projectAdminId("")
                .build();
        //获取cookie
        Cookie[] requestCookies = request.getCookies();
        //获取cookie中的projectIds（父项目及其子项目id）,projectId(当前项目id),userId（当前管理员id）
        if (requestCookies != null) {
            for (Cookie cookie : requestCookies){
                //获取cookie中的projectIds
                if ("projectIds".equals(cookie.getName())) {

                    if (StringUtils.isNotBlank(cookie.getValue())) {
                        JSONArray objects = JSONUtil.parseArray(cookie.getValue());
                        projectInfo.setProjectIdList(objects.toList(Long.class));
                        }
                    }
                //获取cookie中的projectId
                if ("projectId".equals(cookie.getName())) {
                    projectInfo.setProjectId(cookie.getValue());
                    System.err.println("获取cooke的项目id:"+cookie.getValue());
                }
                //获取cookie中的userId
                if ("userId".equals(cookie.getName())) {
                    projectInfo.setProjectAdminId(cookie.getValue());
                }
                //获取cookie中的projectDeptId
                if ("deptId".equals(cookie.getName())) {
                    projectInfo.setProjectDeptId(cookie.getValue());
                }
            }

        }
        ProjectHolder.setProjectInfo(projectInfo);
            return true;
    }
    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, @Nullable Exception ex)  {
        // 清理本地线程
        ProjectHolder.clear();
    }
}