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


import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.SortDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.eactive.eai.rms.common.acl.user.ui.AdminLoginVo;
import com.eactive.eai.rms.common.acl.user.ui.UserAthrRoleChgHistoryUI;
import com.eactive.eai.rms.common.acl.user.ui.UserBizUI;
import com.eactive.eai.rms.common.acl.user.ui.UserRoleUI;
import com.eactive.eai.rms.common.acl.user.ui.UserServicetypeUI;
import com.eactive.eai.rms.common.acl.user.ui.UserUI;
import com.eactive.eai.rms.common.acl.user.ui.UserUISearch;
import com.eactive.eai.rms.common.base.BaseAnnotationController;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.login.SessionManager;
import com.eactive.eai.rms.common.util.IpUtil;
import com.eactive.eai.rms.common.vo.GridResponse;
import com.eactive.eai.rms.data.entity.onl.unifbwk.UnifBwkTpService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;


@Controller
public class UserManController extends BaseAnnotationController {

	private final UserManService userManService;
	private final BizManService bizManService;
	private final ServiceTypeManService serviceTypeManService;
	private final UnifBwkTpService unifBwkTpService;
	private final ObjectMapper objectMapper;


	@Autowired
	public UserManController(UserManService userManService,
							BizManService bizManService,
							ServiceTypeManService serviceTypeManService,
							UnifBwkTpService unifBwkTpService,
							ObjectMapper objectMapper ) {
		this.userManService = userManService;
		this.bizManService = bizManService;
		this.serviceTypeManService = serviceTypeManService;
		this.unifBwkTpService = unifBwkTpService;
		this.objectMapper = objectMapper;
	}


	@GetMapping(value = "/common/acl/user/userMan.view")
	public void view() {
		// view
	}


	@GetMapping(value = "/common/acl/user/userMan.view", params = "cmd=DETAIL")
	public String detailView() {
		return "/common/acl/user/userManDetail";
	}


	/* 상세 팝업 - 역할변경 */
	@GetMapping(value = "/common/acl/user/userMan.view", params = "cmd=POPUP")
	public String detailPopup() {
		return "/common/acl/user/userManPopup";
	}


	/* 상세 팝업 - 권한변경 */
	@GetMapping(value = "/common/acl/user/userMan.view", params = "cmd=POPUP2")
	public String detailPopup2() {
		return "/common/acl/user/userManPopup2";
	}


	/* 상세 팝업 - 사용서비스 */
	@GetMapping(value = "/common/acl/user/userMan.view", params = "cmd=POPUP3")
	public String detailPopup3() {
		return "/common/acl/user/userManPopup3";
	}

	/* 권한변경이력 팝업 - UserAthrRoleChgHistory */
	@GetMapping(value = "/common/acl/user/userMan.view", params = "cmd=POPUP4")
	public String detailPopup4() {
		return "/common/acl/user/userManPopup4";
	}
	

	@PostMapping(value = "/common/acl/user/userMan.json", params = "cmd=LIST")
	public ResponseEntity<GridResponse<UserUI>> selectList(
							@SortDefault("userid") Pageable pageable,
							UserUISearch userUiSearch) {
		Page<UserUI> page = userManService.selectList(pageable, userUiSearch);
		return ResponseEntity.ok(new GridResponse<>(page));
	}


	@PostMapping(value = "/common/acl/user/userMan.json", params = "cmd=DETAIL")
	public ResponseEntity<UserUI> selectDetail(String userId) {
		UserUI userUI = userManService.selectDetail(userId);
		return ResponseEntity.ok(userUI);
	}


	@PostMapping(value = "/common/acl/user/userMan.json", params = "cmd=LIST_INIT_COMBO")
	public ResponseEntity<Map<String, Object>> initCombo() {
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("authRows", userManService.selectRole("Y"));
		return ResponseEntity.ok(resultMap);
	}


	@PostMapping(value = "/common/acl/user/userMan.json", params = "cmd=INSERT")
	public ResponseEntity<Object> insert(HttpServletRequest request, UserUI userUI) {
		AdminLoginVo adminLoginVo = getAdminLoginVo(request);
		
		userManService.insert(userUI,adminLoginVo);
		
		return ResponseEntity.ok().body(
								Collections.singletonMap("result", "success"));
	}

	@PostMapping(value = "/common/acl/user/userMan.json", params = "cmd=UPDATE")
	public ResponseEntity<Object> update(HttpServletRequest request, UserUI userUI) {
		userManService.update(userUI);
		return ResponseEntity.ok().body(
								Collections.singletonMap("result", "success"));
	}


	@PostMapping(value = "/common/acl/user/userMan.json", params = "cmd=DELETE")
	public ResponseEntity<Void> delete(String userId) {
		userManService.delete(userId);
		return ResponseEntity.ok().build();
	}


	@PostMapping(value = "/common/acl/user/userMan.json", params = "cmd=UPDATE_PASSWORD")
	public ResponseEntity<Object> updatePassword(UserUI userUI)
							throws Exception {
		userManService.updatePassword(userUI);
		return ResponseEntity.ok().body(Collections.singletonMap("result",
								"초기화 성공 하였습니다."));
	}


	/* 역할변경 - popup */
	@PostMapping(value = "/common/acl/user/userMan.json", params = "cmd=LIST_USER_ROLE")
	public ResponseEntity<GridResponse<UserRoleUI>> selectUserRoleList(
							String userId) {
		List<UserRoleUI> list = userManService.selectUserRoleList(userId);
		return ResponseEntity.ok(new GridResponse<>(list));
	}


	@PostMapping(value = "/common/acl/user/userMan.json", params = "cmd=TRANSACTION_USER_ROLE")
	public ResponseEntity<Void> transactionUserRole(String userId,
							@RequestParam Map<String, Object> paramMap, HttpServletRequest request)
							throws JsonProcessingException {
		
		List<UserRoleUI> userRoles = objectMapper.readValue(
								(String) paramMap.get("gridData"),
								new TypeReference<List<UserRoleUI>>() {});
		
		AdminLoginVo adminLoginVo = getAdminLoginVo(request);
		
		userManService.transactionUserRoleAndCheckAdmin(userId, userRoles, adminLoginVo);
		return ResponseEntity.ok().build();
	}


	/* 권한변경 - popup2 */
	@PostMapping(value = "/common/acl/user/userMan.json", params = "cmd=LIST_USER_BIZ")
	public ResponseEntity<GridResponse<UserBizUI>> selectListUserBiz(
							String userId, UserBizUI userBizUI) {
		List<UserBizUI> list = bizManService.selectUserBizList(userBizUI);
		return ResponseEntity.ok(new GridResponse<>(list));
	}


	@PostMapping(value = "/common/acl/user/userMan.json", params = "cmd=LIST_BIZ_COUNT")
	public ResponseEntity<Map<String, Integer>> selectListBizCount(
							String searchBzwkName) {
		int bizListCount = Math.toIntExact(unifBwkTpService
								.selectListCount(searchBzwkName));
		return ResponseEntity.ok(Collections.singletonMap("bizCount",
								bizListCount));
	}


	@PostMapping(value = "/common/acl/user/userMan.json", params = "cmd=TRANSACTION_USER_BIZ")
	public ResponseEntity<Void> transactionUserBiz(String userId,
							@RequestParam Map<String, Object> paramMap, HttpServletRequest request)
							throws JsonProcessingException {
		
		List<UserBizUI> userBizUIs = objectMapper.readValue(
								(String) paramMap.get("gridData"),
								new TypeReference<List<UserBizUI>>() {});
		
		bizManService.transactionUserBiz(userId, userBizUIs, getAdminLoginVo(request));
		return ResponseEntity.ok().build();
	}


	/* 서비스타입변경 - popup3 */
	@PostMapping(value = "/common/acl/user/userMan.json", params = "cmd=LIST_SERVICETYPE_COUNT")
	public ResponseEntity<Map<String, Integer>> selectListServiceTypeCount() {
		int dataSourceTypeCount = DataSourceTypeManager
								.getDynamicDataSourceTypes().size();
		return ResponseEntity.ok(Collections.singletonMap("servicetypeCount",
								dataSourceTypeCount));
	}


	@PostMapping(value = "/common/acl/user/userMan.json", params = "cmd=LIST_USER_SERVICETYPE")
	public ResponseEntity<GridResponse<UserServicetypeUI>> selectListUserServiceType(
							String userId, String targetGridYn) {
		List<UserServicetypeUI> list = serviceTypeManService
								.selectUserServiceTypeList(userId,
														targetGridYn);
		return ResponseEntity.ok(new GridResponse<>(list));
	}


	@PostMapping(value = "/common/acl/user/userMan.json", params = "cmd=TRANSACTION_USER_SERVICETYPE")
	public ResponseEntity<String> transactionUserServiceType(String userId,
							@RequestParam Map<String, Object> paramMap, HttpServletRequest request)
							throws JsonProcessingException {
		
		List<UserServicetypeUI> userServicetypeUIs = objectMapper.readValue(
								(String) paramMap.get("gridData"),
								new TypeReference<List<UserServicetypeUI>>() {});

		try {
			serviceTypeManService.transactionUserServiceType(userId, userServicetypeUIs);
			
		} catch (Exception e) {
			return ResponseEntity.internalServerError().body(e.getMessage());
		}

		return ResponseEntity.ok().build();
	}

	/* 권한변경이력 팝업 - POPUP4 */
	@PostMapping(value = "/common/acl/user/userMan.json", params = "cmd=LIST_CHANGE_HISTORY")
	public ResponseEntity<GridResponse<UserAthrRoleChgHistoryUI>> selectList( Pageable pageable, String userId) {
		
		Page<UserAthrRoleChgHistoryUI> page = userManService.selectUserChgHistoryList(pageable, userId);
		return ResponseEntity.ok(new GridResponse<>(page));
	}

	/* 권한 역할 변경이력 관련 */
	private AdminLoginVo getAdminLoginVo(HttpServletRequest request) {
		AdminLoginVo adminLoginVo = new AdminLoginVo();
		adminLoginVo.setLoginIp(IpUtil.getClientIp(request));
		adminLoginVo.setLoginId(SessionManager.getUserId(request));

		return adminLoginVo;
	}
}
