package incheon.ags.ias.user.web;

import incheon.ags.ias.dataHoprReg.service.UserSyncService;
import incheon.ags.ias.user.service.UserService;
import incheon.ags.ias.user.vo.UserSearchVO;
import incheon.ags.ias.user.vo.UserVO;
import incheon.ags.ias.userRole.service.UserRoleService;
import incheon.ags.ias.userRole.vo.UserRoleVO;
import incheon.com.security.annotation.RequireRole;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.egovframe.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

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

/**
 * 사용자 관리 JSP Controller
 * 화면 렌더링용
 */
@Controller
@RequiredArgsConstructor
@Slf4j
@RequireRole(system = "AGS", roles = "ROLE_SUPER_ADMIN", description = "통합관리자 역할 접근 제어")
public class UserController {
    private final UserService userService;
    private final UserSyncService userSyncService;
    private final UserRoleService userRoleService;

    /**
     * 사용자 목록 화면
     */
    @GetMapping("/ags/ias/user/userList.do")
    public String userList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(required = false) String userNm,
            @RequestParam(required = false) String deptCd,
            @RequestParam(required = false) String userStcd,
            ModelMap model) throws Exception {

        // 검색 조건 설정
        UserSearchVO vo = new UserSearchVO();
        vo.setPageIndex(page);
        vo.setUserNm(userNm);
        vo.setDeptCd(deptCd);
        vo.setUserStcd(userStcd);

        // 페이징 정보 세팅
        PaginationInfo paginationInfo = new PaginationInfo();
        paginationInfo.setCurrentPageNo(page);
        paginationInfo.setRecordCountPerPage(vo.getRecordCountPerPage());
        paginationInfo.setPageSize(vo.getPageSize());

        vo.setFirstIndex(paginationInfo.getFirstRecordIndex());
        vo.setLastIndex(paginationInfo.getLastRecordIndex());
        vo.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());

        // 사용자 리스트
        List<Map<String, Object>> userList = userService.selectUserList(vo);
        
        // 검색 조건이 적용된 총 카운트
        int totalCount = userService.selectUserCnt(vo);
        paginationInfo.setTotalRecordCount(totalCount);

        // 부서 목록 조회 (검색 조건용)
        List<Map<String, Object>> deptList = userService.deptList();

        model.addAttribute("userList", userList);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("paginationInfo", paginationInfo);
        model.addAttribute("searchVO", vo);
        model.addAttribute("deptList", deptList);
        model.addAttribute("deptCd", deptCd);
        model.addAttribute("userStcd", userStcd);

        return "/ags/ias/user/userList";
    }

    /**
     * 사용자 상세 화면
     */
    @GetMapping("/ags/ias/user/userDetail.do")
    public String userDetail(
            @RequestParam("userId") String userId,
            ModelMap model) throws Exception {

        try {
            UserVO vo = new UserVO();
            vo.setUserId(userId);
            UserVO userDetail = userService.selectUserDetail(vo);
            
            if (userDetail != null) {
                model.addAttribute("userDetail", userDetail);
            } else {
                log.error("해당 사용자를 찾을 수 없습니다. userId: {}", userId);
                model.addAttribute("errorMessage", "해당 사용자를 찾을 수 없습니다.");
            }
        } catch (Exception e) {
            log.error("사용자 상세 조회 중 오류 발생", e);
            model.addAttribute("errorMessage", "사용자 정보 조회 중 오류가 발생했습니다: " + e.getMessage());
        }

        return "ags/ias/user/userDetail";
    }

    /**
     * 사용자 등록 화면
     */
    @GetMapping("/ags/ias/user/userRegist.do")
    public String userRegist(ModelMap model) throws Exception {

        try {
            // 부서 목록 조회 (동적 로딩으로 변경되었지만 호환성 유지)
            List<Map<String, Object>> deptList = userService.deptList();
            model.addAttribute("deptList", deptList);

            // 직급 목록 조회 (동적 로딩으로 변경되었지만 호환성 유지)
            List<Map<String, Object>> jbgdList = userService.jbgdList();
            model.addAttribute("jbgdList", jbgdList);

        } catch (Exception e) {
            log.error("사용자 등록 페이지 로딩 중 오류 발생", e);
            model.addAttribute("errorMessage", "페이지 로딩 중 오류가 발생했습니다: " + e.getMessage());
        }

        return "ags/ias/user/userRegist";
    }

    /**
     * 사용자 수정 화면
     */
    @GetMapping("/ags/ias/user/userModify.do")
    public String userModify(
            @RequestParam("userId") String userId,
            ModelMap model) throws Exception {

        try {
            // 사용자 상세 정보 조회
            UserVO vo = new UserVO();
            vo.setUserId(userId);
            UserVO userDetail = userService.selectUserDetail(vo);
            
            if (userDetail != null) {
                model.addAttribute("userDetail", userDetail);
            } else {
                log.error("해당 사용자를 찾을 수 없습니다. userId: {}", userId);
                model.addAttribute("errorMessage", "해당 사용자를 찾을 수 없습니다.");
                return "redirect:/ags/ias/user/userList.do";
            }

            // 부서 목록 조회 (동적 로딩으로 변경되었지만 호환성 유지)
            List<Map<String, Object>> deptList = userService.deptList();
            model.addAttribute("deptList", deptList);

            // 직급 목록 조회 (동적 로딩으로 변경되었지만 호환성 유지)
            List<Map<String, Object>> jbgdList = userService.jbgdList();
            model.addAttribute("jbgdList", jbgdList);

        } catch (Exception e) {
            log.error("사용자 수정 페이지 로딩 중 오류 발생", e);
            model.addAttribute("errorMessage", "페이지 로딩 중 오류가 발생했습니다: " + e.getMessage());
            return "redirect:/ags/ias/user/userList.do";
        }

        return "ags/ias/user/userModify";
    }

    /**
     * 부서 목록 조회 API (AJAX용)
     * @deprecated 동적 로딩으로 변경되어 사용하지 않음
     */
    @GetMapping("/ags/ias/user/api/deptList.do")
    @Deprecated
    public List<Map<String, Object>> getDeptList() throws Exception {
        log.warn("부서 목록 API는 더 이상 사용되지 않습니다. 공통코드 API를 사용하세요.");
        return userService.deptList();
    }

    /**
     * 직급 목록 조회 API (AJAX용)
     * @deprecated 동적 로딩으로 변경되어 사용하지 않음
     */
    @GetMapping("/ags/ias/user/api/jbgdList.do")
    @Deprecated
    public List<Map<String, Object>> getJbgdList() throws Exception {
        log.warn("직급 목록 API는 더 이상 사용되지 않습니다. 공통코드 API를 사용하세요.");
        return userService.jbgdList();
    }

    /**
     * 사용자 선택 팝업 화면
     * AJAX 레이어 팝업으로 사용됨
     */
    @GetMapping("/ags/ias/user/userSelectPopup.do")
    public String userSelectPopup(ModelMap model) throws Exception {
        log.debug("사용자 선택 팝업 화면 요청");
        return "/ags/ias/user/userSelectPopup";
    }

    /**
     * 사용자 변경 관리 (이력 목록) 화면
     */
    @GetMapping("/ags/ias/user/userHstryList.do")
    public String userHstryList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(required = false) String userStcd,
            @RequestParam(required = false) String deptCd,
            @RequestParam(required = false) String userNm,
            ModelMap model) throws Exception {

        // 검색 조건 설정
        Map<String, Object> param = new HashMap<>();
        param.put("userStcd", userStcd);
        param.put("deptCd", deptCd);
        param.put("userNm", userNm);

        // 페이징 정보 세팅
        int recordCountPerPage = 10;
        int pageSize = 10;

        PaginationInfo paginationInfo = new PaginationInfo();
        paginationInfo.setCurrentPageNo(page);
        paginationInfo.setRecordCountPerPage(recordCountPerPage);
        paginationInfo.setPageSize(pageSize);

        param.put("firstIndex", paginationInfo.getFirstRecordIndex());
        param.put("recordCountPerPage", recordCountPerPage);

        // 총 건수 조회
        int totalCount = userSyncService.selectUserHstryCnt(param);
        paginationInfo.setTotalRecordCount(totalCount);

        // 이력 목록 조회
        List<Map<String, Object>> hstryList = userSyncService.selectUserHstryList(param);

        // searchVO 생성
        Map<String, Object> searchVO = new HashMap<>();
        searchVO.put("userStcd", userStcd);
        searchVO.put("deptCd", deptCd);
        searchVO.put("userNm", userNm);

        model.addAttribute("hstryList", hstryList);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("paginationInfo", paginationInfo);
        model.addAttribute("searchVO", searchVO);

        return "/ags/ias/user/userHstryList";
    }

    /**
     * 사용자 변경 이력 상세 화면
     */
    @GetMapping("/ags/ias/user/userHstryDetail.do")
    public String userHstryDetail(
            @RequestParam("userHstrySn") Long userHstrySn,
            ModelMap model) throws Exception {

        // 1. 이력 상세 조회 (변경 전 데이터)
        Map<String, Object> hstryDetail = userSyncService.selectUserHstryDetail(userHstrySn);

        if (hstryDetail == null) {
            log.error("해당 이력을 찾을 수 없습니다. userHstrySn: {}", userHstrySn);
            model.addAttribute("errorMessage", "해당 이력을 찾을 수 없습니다.");
            return "redirect:/ags/ias/user/userHstryList.do";
        }

        model.addAttribute("hstryDetail", hstryDetail);

        String cngypCd = (String) hstryDetail.get("cngypCd");
        String userUnqId = (String) hstryDetail.get("userUnqId");
        String userId = (String) hstryDetail.get("userId");

        // 2. 현재 사용자 정보 조회 (변경유형과 관계없이 항상 조회)
        Map<String, Object> currentUser = null;
        List<Map<String, Object>> userRole = null;

        if (userUnqId != null) {
            // 현재 사용자 정보 조회 (전체 필드 - Map으로 조회)
            currentUser = userSyncService.selectUserMapByUnqId(userUnqId);

            if (currentUser != null) {
                // 보유 시스템 권한 조회
                UserRoleVO roleVO = new UserRoleVO();
                roleVO.setUserId((String) currentUser.get("userId"));
                userRole = userRoleService.selectUserRole(roleVO);
            }
        }

        model.addAttribute("currentUser", currentUser);
        model.addAttribute("userRole", userRole);
        model.addAttribute("isDeleted", "D".equals(cngypCd));
        model.addAttribute("isCreated", "C".equals(cngypCd));

        return "/ags/ias/user/userHstryDetail";
    }
}
