package com.dbnt.faisp.organMgt;

import com.dbnt.faisp.codeMgt.service.CodeMgtService;
import com.dbnt.faisp.codeMgt.model.CodeMgt;
import com.dbnt.faisp.organMgt.service.OrganConfigService;
import com.dbnt.faisp.organMgt.model.OrganConfig;
import com.dbnt.faisp.userInfo.model.UserInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;


@RestController
@RequiredArgsConstructor
@RequestMapping("/organMgt")
public class OrganConfigController {
  private final OrganConfigService organConfigService;
  private final CodeMgtService codeMgtService;

  @GetMapping("/organMgtPage")
  public ModelAndView organMgtPage(UserInfo userInfo) {
    ModelAndView mav = new ModelAndView("adminPage/organMgt/organMgt");
    mav.addObject("searchParams", userInfo);
    return mav;
  }

  @GetMapping("/selectOrganList")
  public List<OrganConfig> selectOrganList(){
    List<CodeMgt> organCdList = codeMgtService.selectCodeMgtList("OG");
    List<OrganConfig> organConfigList = organConfigService.selectSavedOrganList();
    for(CodeMgt organCode: organCdList){
      if(!organCode.getItemCd().equals("OG001")){
        boolean usedFlag = false;
        for(OrganConfig organConfig: organConfigList){
          if(organCode.getItemCd().equals(organConfig.getOrganCd())){
            usedFlag = true;
            organConfig.setOrganNm(organCode.getItemValue());
            organConfig.setUseState("T");
            break;
          }
        }
        if(!usedFlag){
          OrganConfig organConfig = new OrganConfig();
          organConfig.setOrganCd(organCode.getItemCd());
          organConfig.setOrganNm(organCode.getItemValue());
          organConfig.setUseState("F");
          organConfigList.add(organConfig);
        }
      }
    }
    return organConfigList;
  }

  @PostMapping("/saveOrganConfig")
  @ResponseBody
  public Integer saveOrganConfig(@RequestBody List<OrganConfig> organConfigList){
    return organConfigService.saveOrganConfig(organConfigList);
  }

}
