package incheon.res.rdm.ui.usrinfo.web;


import incheon.com.cmm.ResponseCode;
import incheon.com.cmm.api.DefaultApiResponse;
import incheon.com.security.vo.LoginVO;
import incheon.res.rdm.com.code.service.RdmComCodeService;
import incheon.res.rdm.ui.usrinfo.service.RdmUiUsrinfoService;
import incheon.res.rdm.ui.usrinfo.vo.RdmUiUsrinfo;
import incheon.res.rdm.ui.usrinfo.vo.RdmUiUsrinfoVO;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.egovframe.rte.fdl.property.EgovPropertyService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("${api.rps-path}")
public class RdmUiUsrinfoController {

	protected Log log = LogFactory.getLog(this.getClass());

	@Resource
    private RdmUiUsrinfoService rdmUiUsrinfoService;
    @Resource
    protected RdmComCodeService rdmComCodeService;
	@Resource(name = "propertiesService")
	protected EgovPropertyService propertiesService;

    public static final int KEY_SIZE = 2048;

  

	/**
	 * @MethodDESC : 사용자 정보 수정 화면
	 */
	@RequestMapping(value = "/RdmUiUsrInfoU010.do")
	public String updateUsrinfoView(
			@ModelAttribute("loginUser") LoginVO loginVO,
			HttpServletRequest request,
			@ModelAttribute("RdmUiUsrinfoVO") RdmUiUsrinfoVO vo,
			ModelMap model
	) throws Exception{

		String sessionUserId = loginVO.getUserUnqId();
		vo.setUserAcntMngNo(sessionUserId);

		RdmUiUsrinfo rdmUiUsrinfo = rdmUiUsrinfoService.selectUsrinfo(vo);

		model.addAttribute("rdmUiUsrinfo", rdmUiUsrinfo);

		return "res/rdm/ui/usrinfo/RdmUiUsrInfoU010";
	}

	/**
	 * @MethodDESC : 사용자 정보 수정
	 */
	@RequestMapping(value = "/RdmUiUsrinfoU011.do")
	public ResponseEntity<DefaultApiResponse<Map<String, Object>>> updateUsrinfo(
			@ModelAttribute RdmUiUsrinfoVO vo,
			HttpServletRequest request,
			BindingResult bindingResult
	) throws Exception{

		if (bindingResult.hasErrors()) {
			Map<String, String> errors = new HashMap<>();
			bindingResult.getFieldErrors().forEach(error -> {
				String fieldName = error.getField();
				String errorMessage = error.getDefaultMessage();
				errors.put(fieldName, errorMessage);
			});

			DefaultApiResponse<Map<String, Object>> response = DefaultApiResponse.<Map<String, Object>>builder()
					.code(ResponseCode.INPUT_ERROR.getCode())
					.message("입력값 검증 오류가 발생했습니다.")
					.data((Map<String, Object>) (Object) errors)
					.timestamp(java.time.LocalDateTime.now())
					.error("ValidationException")
					.build();

			return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
		}

		int result = 0;

		try{
				result = rdmUiUsrinfoService.updateUserWithoutPwd(vo);

		}catch (IllegalStateException e) {
			log.error("사용자 정보 수정 실패", e);
			return ResponseEntity.badRequest().build();
		}

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("result", result);

		return ResponseEntity.ok(DefaultApiResponse.success(resultMap));
	}
	
	@RequestMapping(value = "/RdmUiUsrinfoU012.do")
	public ResponseEntity<DefaultApiResponse<Map<String, Object>>> deptLink(
			@ModelAttribute("loginUser") LoginVO loginVO,
			@ModelAttribute RdmUiUsrinfoVO vo
	) throws Exception{

		vo.setBzentyInstMngNo(loginVO.getRoadMngInstCd());
		vo.setBzentyInstMngNo(vo.getBzentyInstMngNo().substring(0,3));

		Map<String, Object> resultMap = new HashMap<String, Object>();
		String result = "";
		try{
			result = rdmUiUsrinfoService.getDeptCode(vo);
			resultMap.put("deptCode", result);

			result = rdmUiUsrinfoService.getMinwonDeptCode(vo);
			resultMap.put("minwonCode", result);
		}catch (IllegalStateException e) {
			log.error("사용자 정보 조회 중 오류 발생", e);
			return ResponseEntity.badRequest().build();
		}

		return ResponseEntity.ok(DefaultApiResponse.success(resultMap));
	}
	
	
	
}
