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

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.portalorg.PortalOrgUISearch;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.eactive.eai.common.util.SystemUtil;
import com.eactive.eai.rms.onl.common.exception.BizException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.MediaType;
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 org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;

@Slf4j
@Controller
@RequiredArgsConstructor
public class PortalOrgManController extends BaseAnnotationController {

    private final PortalOrgManService portalOrgManService;
    private final ComboService comboService;

    @GetMapping(value = "/onl/apim/portalorg/portalOrgMan.view")
    public void view(Model model) {
        model.addAttribute("hardDeleteEnabled", portalOrgManService.isHardDeleteEnabled());
    }

    @GetMapping(value = "/onl/apim/portalorg/portalOrgMan.view", params = "cmd=DETAIL")
    public String detailNewView() {
        return "/onl/apim/portalorg/portalOrgManDetail";
    }

    @PostMapping(value = "/onl/apim/portalorg/portalOrgMan.json", params = "cmd=LIST")
    public ResponseEntity<GridResponse<PortalOrgUI>> selectList(@SortDefault(sort = "createdDate", direction = Sort.Direction.DESC) Pageable pageable,
        PortalOrgUISearch portalOrgUISearch) {
        portalOrgUISearch.setIncludeRemoved(!SystemUtil.isProdServer());
        Page<PortalOrgUI> page = portalOrgManService.selectList(pageable, portalOrgUISearch);
        return ResponseEntity.ok(new GridResponse<>(page));
    }

    @PostMapping(value = "/onl/apim/portalorg/portalOrgMan.json", params = "cmd=DETAIL")
    public ResponseEntity<Map<String, Object>> selectDetail(String id) {
        Map<String, Object> result = portalOrgManService.selectDetailWithUsers(id);
        return ResponseEntity.ok(result);
    }

    @PostMapping(value = "/onl/apim/portalorg/portalOrgMan.json", params = "cmd=LIST_INIT_COMBO")
    public ResponseEntity<Map<String, Object>> initCombo() {
        List<ComboVo> approvalStatusList = comboService.getMonitoringCodeSortedBySeq("APPROVE_STATUS_CODE"); // 승인상태코드
        List<ComboVo> orgStatusList = comboService.getMonitoringCodeSortedBySeq("STATUS_CODE").stream()
            .filter(e -> !e.getCode().equals("INACTIVE")).collect(Collectors.toList()); // 상태코드

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("approvalStatusRows", approvalStatusList);
        resultMap.put("orgStatusRows", orgStatusList);
        resultMap.put("isProdServer", SystemUtil.isProdServer());
        return ResponseEntity.ok(resultMap);
    }

    @PostMapping(value = "/onl/apim/portalorg/portalOrgMan.json", params = "cmd=INSERT")
    public ResponseEntity<String> insert(PortalOrgUI portalOrgUI) throws IOException {
        portalOrgManService.insert(portalOrgUI);
        return ResponseEntity.ok().build();
    }

    @PostMapping(value = "/_onl/apim/portalorg/portalOrgMan.json", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> apiRequest(@RequestHeader(value = "action", required = false, defaultValue = "none") String action, @RequestBody PortalOrgUI portalOrgUI) throws IOException {
        portalOrgUI.setCompRegFile(null);
        if (action.equalsIgnoreCase("insert")) {
            portalOrgManService.insert(portalOrgUI);
        } else if (action.equalsIgnoreCase("update")) {
            portalOrgManService.update(portalOrgUI);
        }
        return ResponseEntity.ok().build();
    }

    @PostMapping(value = "/onl/apim/portalorg/portalOrgMan.json", params = "cmd=UPDATE")
    public ResponseEntity<Void> update(PortalOrgUI portalOrgUI) throws IOException {
        portalOrgManService.update(portalOrgUI);
        return ResponseEntity.ok().build();
    }

    @PostMapping(value = "/onl/apim/portalorg/portalOrgMan.json", params = "cmd=DELETE")
    public ResponseEntity<Void> delete(String id) {
        portalOrgManService.removeOrg(id);
        return ResponseEntity.ok().build();
    }

    @PostMapping(value = "/onl/apim/portalorg/portalOrgMan.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())) {
                    portalOrgManService.removeOrg(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/portalorg/portalOrgMan.json", params = "cmd=HARD_DELETE")
    public ResponseEntity<Map<String, Object>> hardDelete(String id) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            portalOrgManService.hardDeleteOrg(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/portalorg/portalOrgMan.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 java.util.ArrayList<>();

            for (String id : idArray) {
                if (StringUtils.isNotBlank(id.trim())) {
                    try {
                        portalOrgManService.hardDeleteOrg(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/portalorg/portalOrgMan.json", params = "cmd=POPUP_LIST")
    public ResponseEntity<GridResponse<PortalOrgUI>> selectOrgList(@SortDefault(sort = "createdDate", direction = Sort.Direction.DESC) Pageable pageable,
        PortalOrgUISearch portalOrgUISearch) {
        Page<PortalOrgUI> page = portalOrgManService.selectList(pageable, portalOrgUISearch);
        return ResponseEntity.ok(new GridResponse<>(page));
    }

}
