package com.eactive.eai.rms.common.acl.user;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.login.SessionManager;
import com.eactive.eai.rms.common.util.CommonConstants;
import com.eactive.eai.rms.data.entity.man.menu.MenuService;
import com.eactive.eai.rms.data.entity.man.role.RoleMenuAuthService;
import com.eactive.eai.rms.data.entity.man.user.UserInfoService;
import com.eactive.eai.rms.data.entity.man.user.UserRoleService;
import com.eactive.eai.rms.data.entity.onl.bzwkdstcd.UserBusinessId;
import com.eactive.eai.rms.data.entity.onl.bzwkdstcd.UserBusinessService;
import com.eactive.eai.rms.data.entity.onl.unifbwk.UnifBwkTpService;

public class RecordAuthUtil {
	
	/**
	 * record 제어를 위해 해당 아이디의 모든 업무권한 가져오기
	 */
	public static List<String> getRecordAuthList(String empno) throws Exception {
		List<String> list = new ArrayList<>();
		UnifBwkTpService unifBwkTpService =  ApplicationContextProvider.getContext().getBean(UnifBwkTpService.class);
		UserBusinessService userBusinessService =  ApplicationContextProvider.getContext().getBean(UserBusinessService.class);

		List<Map<String, Object>> dataList = userBusinessService.getRecordAuthList(empno);

		if (!dataList.isEmpty() && "*   ".equals((dataList.get(0)).get("BZCD"))) {
			dataList = unifBwkTpService.getRecordAuthListALL(); 
		}
		for (Map<String, Object> map : dataList) {
			list.add((String) map.get("BZCD"));
		}
		
		return list;
	}

	/**
	 * record 제어를 위해 해당 아이디, 업무권한이 등록되었는지 확인 - 등록되었으면 Y를 return
	 */
	public static String getRecordAuthYn(String empno, String bzCd) throws Exception {

		UserBusinessService userBusinessService = ApplicationContextProvider.getContext().getBean(UserBusinessService.class);
		UserInfoService userInfoService = ApplicationContextProvider.getContext().getBean(UserInfoService.class);
		List<String> roleId = Arrays.asList(CommonConstants.EAI_APPROVER, CommonConstants.EAI_MANAGER);
		
		if (StringUtils.isEmpty(bzCd)) {  // 업무코드가 없는 ui일경우 -> EAI 운영자와 승인자만 진행
			// EAI 팀인지 확인 - EAI팀이면 true "Y"
			return userInfoService.isEAITeam(empno, roleId) ?  "Y" : "N";
		} else {
			return userBusinessService.findById(new UserBusinessId(empno, bzCd)).isPresent() ? "Y" : "N";
		} 
	}

	/**
	 * 권한그룹이 admin, eai_manager 인 경우에는 업무그룹 필드가 공백이 항목까지 모두 조회한다.
	 */
	public static String getRecordAuthQuery2(HttpServletRequest request, String empno) throws Exception {
		List<String> list = getRecordAuthList(empno);
		StringBuffer st = new StringBuffer();
		String separator = "";
		
		if (!list.isEmpty()) {
			for(String bzcd : list) {
				st.append(separator);
				st.append("'").append(bzcd).append("'");
				separator = ", ";
			}
			
			MonitoringContext monitoringContext = ApplicationContextProvider.getContext().getBean(MonitoringContext.class);
			String tranTrackingPeriod = monitoringContext.getStringProperty(MonitoringContext.RMS_ALL_ROLE_ID, "admin");
			
			if (tranTrackingPeriod.contains(SessionManager.getRoleIdString(request)) ) {
				st.append(", ").append("''");
			}
		}

		return st.toString();
	}

	/**
	 * 제어를 위한 쿼리조건 생성 ( 업무그룹 코드 ) - 사용자 그룹이 admin, eai_manager 중의 하나인 경우 업무그룹코드가
	 * null 인 것도 포함해서 조회한다.
	 */
	public static String getRecordAuthQuery2(HttpServletRequest request) throws Exception {
		String userId = SessionManager.getUserId(request);

		if (StringUtils.isEmpty(userId)) {
			throw new Exception("로그인 되지 않았습니다.");
		}

		return RecordAuthUtil.getRecordAuthQuery2(request, userId);
	}

	/**
	 * empno으로 roleId 가져오기
	 */
	public static String getRoleId(String empno) throws Exception {
		UserRoleService userRoleService = ApplicationContextProvider.getContext().getBean(UserRoleService.class);
		return userRoleService.getRoleId(empno);
	}

	/**
	 * 현재 메뉴위치 - 메뉴 아이디로 현재 메뉴위치구하기
	 */
	public static String getPosition(String menuId) throws Exception {
		MenuService menuService = ApplicationContextProvider.getContext().getBean(MenuService.class);
		return menuService.getPosition(menuId);
	}
	
	/**
	 * 메뉴 권한 가져오기
	 */
	public static String getMenuAuth(HttpServletRequest request, String empno, String menuId, String serviceType)
			throws Exception {
		RoleMenuAuthService roleMenuAuthService = ApplicationContextProvider
				.getContext()
				.getBean(RoleMenuAuthService.class);
		String authCode = roleMenuAuthService.getRoleList(empno, menuId, serviceType);
		return noCheckRole(request, authCode);
	}

	/**
	 * 메뉴 권한 가져오기
	 * @return 권한코드
	 */
	public static String getMenuUrlAuth(HttpServletRequest request, String empno, String url, String serviceType)
			throws Exception {
		MenuService menuService = ApplicationContextProvider.getContext().getBean(MenuService.class);
		String authCode = menuService.getUrlAuth(empno, url, serviceType);
		return noCheckRole(request, authCode);
	}
	
	public static String noCheckRole(HttpServletRequest request,String authCode){
		return StringUtils.isNotEmpty(authCode) ? authCode : "R"; // 읽기권한
	}
}
