package com.eactive.eai.rms.onl.apim.portaluser;

import java.util.*;
import java.util.stream.Collectors;

import com.eactive.apim.portal.portaluser.entity.PortalUserEnums;
import com.eactive.eai.common.util.SystemUtil;
import com.eactive.eai.rms.onl.common.exception.BizException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.SortDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import com.eactive.eai.rms.common.base.BaseAnnotationController;
import com.eactive.eai.rms.common.combo.ComboService;
import com.eactive.eai.rms.common.combo.ComboVo;
import com.eactive.eai.rms.common.vo.GridResponse;
import com.eactive.eai.rms.data.entity.onl.apim.portaluser.PortalUserUISearch;

import lombok.RequiredArgsConstructor;

@Controller
@RequiredArgsConstructor
public class PortalUserManController extends BaseAnnotationController {

	private final PortalUserManService portalUserManService;
	private final ComboService comboService;

	@GetMapping(value = "/onl/apim/portaluser/portalUserMan.view")
	public void view(Model model) {
		model.addAttribute("hardDeleteEnabled", portalUserManService.isHardDeleteEnabled());
	}

	@GetMapping(value = "/onl/apim/portaluser/portalUserMan.view", params = "cmd=DETAIL")
	public String detailNewView() {
		return "/onl/apim/portaluser/portalUserManDetail";
	}

	@PostMapping(value = "/onl/apim/portaluser/portalUserMan.json", params = "cmd=LIST")
	public ResponseEntity<GridResponse<PortalUserUI>> selectList(@SortDefault(sort = "createdDate", direction = Sort.Direction.DESC) Pageable pageable,
			PortalUserUISearch portalUserUISearch) {
		portalUserUISearch.setIncludeRemoved(!SystemUtil.isProdServer());
		Page<PortalUserUI> page = portalUserManService.selectList(pageable, portalUserUISearch);
		return ResponseEntity.ok(new GridResponse<>(page));
	}

	// 2025.09.23 : 마스킹 해제를 기본상태로 변경 / Rinjae
	/* 마스킹 처리된 값
	* 수정버튼 비활성화. -> "마스킹해제" 버튼 클릭후 언마스크
	* */
	@PostMapping(value = "/onl/apim/portaluser/portalUserMan.json", params = "cmd=DETAIL")
	public ResponseEntity<PortalUserUI> selectDetail(String id) {
		PortalUserUI portalUserUI = portalUserManService.selectDetail(id, false);
		return ResponseEntity.ok(portalUserUI);
	}

	@PostMapping(value = "/onl/apim/portaluser/portalUserMan.json", params = "cmd=UNMASK")
	public ResponseEntity<PortalUserUI> selectDetailUnmask(String id, String reason) {
		if (StringUtils.isBlank(reason)) {
			throw new BizException("마스킹 해제 사유를 입력해 주세요.");
		}
		PortalUserUI portalUserUI = portalUserManService.selectDetail(id, false);
		return ResponseEntity.ok(portalUserUI);
	}

	@PostMapping(value = "/onl/apim/portaluser/portalUserMan.json", params = "cmd=LIST_INIT_COMBO")
	public ResponseEntity<Map<String, Object>> initCombo() {
		List<ComboVo> portalOrgList = comboService.getFromPortalOrgName();// 기관코드

		List<ComboVo> approvalStatusList = Arrays.stream(PortalUserEnums.ApprovalStatus.values())
				.map(status -> {
					ComboVo vo = new ComboVo();
					vo.setCode(status.name());
					vo.setCodename(status.getDescription());
					return vo;
				}).collect(Collectors.toList());

		List<ComboVo> userStatusList = Arrays.stream(PortalUserEnums.UserStatus.values())
				.map(status -> {
					ComboVo vo = new ComboVo();
					vo.setCode(status.name());
					vo.setCodename(status.getDescription());
					return vo;
				}).collect(Collectors.toList());

		List<ComboVo> roleCodeList = Arrays.stream(PortalUserEnums.RoleCode.values())
				.map(status -> {
					ComboVo vo = new ComboVo();
					vo.setCode(status.name());
					vo.setCodename(status.getDescription());
					return vo;
				}).collect(Collectors.toList());

		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("orgRows", portalOrgList);
		resultMap.put("approvalStatusRows", approvalStatusList);
		resultMap.put("userStatusRows", userStatusList);
		resultMap.put("roleCodeRows", roleCodeList);
		resultMap.put("isProdServer", SystemUtil.isProdServer());

		// 휴대폰번호 중복 허용안함 여부 및 중복 사용자 수 (배너 노출용)
		Map<String, Object> mobileDuplicateInfo = portalUserManService.getMobileDuplicateInfo();
		resultMap.put("mobileDuplicateCheckEnabled", mobileDuplicateInfo.get("enabled"));
		resultMap.put("mobileDuplicateUserCount", mobileDuplicateInfo.get("count"));

		return ResponseEntity.ok(resultMap);
	}

	@PostMapping(value = "/onl/apim/portaluser/portalUserMan.json", params = "cmd=INSERT")
	public ResponseEntity<String> insert(PortalUserUI portalUserUI) throws Exception {
		portalUserManService.insert(portalUserUI);
		return ResponseEntity.ok().build();
	}

	@PostMapping(value = "/onl/apim/portaluser/portalUserMan.json", params = "cmd=UPDATE")
	public ResponseEntity<String> update(PortalUserUI portalUserUI) {
		portalUserManService.update(portalUserUI);
		return ResponseEntity.ok().build();
	}

	@PostMapping(value = "/onl/apim/portaluser/portalUserMan.json", params = "cmd=DELETE")
	public ResponseEntity<Void> delete(String id) {
		portalUserManService.removeUser(id);		// 실제 삭제가 아님. 상태 및 데이터 변경
		return ResponseEntity.ok().build();
	}

	@PostMapping(value = "/onl/apim/portaluser/portalUserMan.json", params = "cmd=DELETE_MULTIPLE")
	public ResponseEntity<Map<String, Object>> deleteMultiple(String ids) {
		Map<String, Object> resultMap = new HashMap<>();
		try {
			if (StringUtils.isBlank(ids)) {
				resultMap.put("status", "fail");
				resultMap.put("message", "삭제할 사용자를 선택해주세요.");
				return ResponseEntity.ok(resultMap);
			}

			String[] idArray = ids.split(",");
			for (String id : idArray) {
				if (StringUtils.isNotBlank(id.trim())) {
					portalUserManService.removeUser(id.trim());
				}
			}

			resultMap.put("status", "success");
			resultMap.put("message", idArray.length + "명의 사용자가 삭제되었습니다.");
		} catch (Exception e) {
			resultMap.put("status", "fail");
			resultMap.put("message", "삭제 중 오류가 발생했습니다: " + e.getMessage());
		}
		return ResponseEntity.ok(resultMap);
	}

	@PostMapping(value = "/onl/apim/portaluser/portalUserMan.json", params = "cmd=HARD_DELETE")
	public ResponseEntity<Map<String, Object>> hardDelete(String id) {
		Map<String, Object> resultMap = new HashMap<>();
		try {
			portalUserManService.hardDeleteUser(id);
			resultMap.put("status", "success");
			resultMap.put("message", "완전삭제가 완료되었습니다.");
		} catch (BizException e) {
			resultMap.put("status", "fail");
			resultMap.put("message", e.getMessage());
		} catch (Exception e) {
			resultMap.put("status", "fail");
			resultMap.put("message", "완전삭제 중 오류가 발생했습니다: " + e.getMessage());
		}
		return ResponseEntity.ok(resultMap);
	}

	@PostMapping(value = "/onl/apim/portaluser/portalUserMan.json", params = "cmd=HARD_DELETE_MULTIPLE")
	public ResponseEntity<Map<String, Object>> hardDeleteMultiple(String ids) {
		Map<String, Object> resultMap = new HashMap<>();
		try {
			if (StringUtils.isBlank(ids)) {
				resultMap.put("status", "fail");
				resultMap.put("message", "완전삭제할 사용자를 선택해주세요.");
				return ResponseEntity.ok(resultMap);
			}

			String[] idArray = ids.split(",");
			int successCount = 0;
			List<String> failMessages = new ArrayList<>();

			for (String id : idArray) {
				if (StringUtils.isNotBlank(id.trim())) {
					try {
						portalUserManService.hardDeleteUser(id.trim());
						successCount++;
					} catch (BizException e) {
						failMessages.add(e.getMessage());
					}
				}
			}

			if (failMessages.isEmpty()) {
				resultMap.put("status", "success");
				resultMap.put("message", successCount + "명의 사용자가 완전삭제되었습니다.");
			} else {
				resultMap.put("status", "fail");
				resultMap.put("message", "완전삭제 실패: " + String.join(", ", failMessages)
						+ (successCount > 0 ? " (" + successCount + "건 성공)" : ""));
			}
		} catch (Exception e) {
			resultMap.put("status", "fail");
			resultMap.put("message", "완전삭제 중 오류가 발생했습니다: " + e.getMessage());
		}
		return ResponseEntity.ok(resultMap);
	}

	@PostMapping(value = "/onl/apim/portaluser/portalUserMan.json", params = "cmd=CHECK_ID")
	public ResponseEntity<Object> checkDuplicateId(String loginId) {
		String result = portalUserManService.checkDuplicateId(loginId) ? "success" : "";
		return ResponseEntity.ok().body(Collections.singletonMap("result", result));
	}
	
	@PostMapping(value = "/onl/apim/portaluser/portalUserMan.json", params = "cmd=PASSWORD_RESET")
	public ResponseEntity<Void> passwordReset(String id) {
		portalUserManService.passwordReset(id);
		return ResponseEntity.ok().build();
	}

}
