package easydo.technology.core;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import easydo.technology.core.processors.UserProcessor;
import zmo.technology.lite.core.ZeroController;
import zmo.technology.lite.core.ZeroRequestGuider;

public abstract class ZeroCoreSpringController extends ZeroController {

    public static final String REQUEST_USER = "REQUEST_USER";

    protected ZeroCoreSpringController(String prefix) {
        super(prefix);
    }

    private void fetchChildDeptProjects(UserProcessor userProcessor, SpringRequestUser user, Long deptID)
            throws SQLException {
        Set<Long> childIds = userProcessor.fetchChildDeptIDs(deptID);
        if (!childIds.isEmpty()) {
            user.getProjectInfos().addAll(userProcessor.fetchChildDeptProjectInfos(deptID));
            for (Long childId : childIds)
                fetchChildDeptProjects(userProcessor, user, childId);
        }
    }

    @Override
    protected void before(ZeroRequestGuider guider) throws Exception {
        UserProcessor userProcessor = UserProcessor.build(guider);
        SpringRequestUser user = new SpringRequestUser();
        userProcessor.fetchUserProjectInfos(user);
        if (user.getDeptID() == 1) {
            user.setProjectUser(false);
            userProcessor.fetchAllProjectInfos(user);
        } else if (!user.isProjectUser()) {
            userProcessor.fetchDeptProjectInfos(user);
            fetchChildDeptProjects(userProcessor, user, user.getDeptID());
        }
        //查询用户授权项目
        List<FactoryProjectInfo> authProjectList = userProcessor.fetchUserAuthProjectList(user.getUserID());
        if (!authProjectList.isEmpty()) {
            List<FactoryProjectInfo> existList;
            if (user.getProjectInfos() != null) {
                existList = user.getProjectInfos();
            } else {
                existList = new ArrayList<>();
            }
            existList.addAll(authProjectList);
            user.setProjectInfos(existList);
        }
        if (user.getProjectInfos() != null) {
            for (FactoryProjectInfo projectInfo : user.getProjectInfos()) {
                userProcessor.fetchAllProjectInfoPosition(projectInfo);
            }
        }
        guider.addJSONStaging(REQUEST_USER, user);
    }
}
