package itn.let.org.web;

import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;

import egovframework.rte.fdl.idgnr.EgovIdGnrService;
import egovframework.rte.fdl.security.userdetails.util.EgovUserDetailsHelper;
import itn.com.cmm.LoginVO;
import itn.let.org.service.LocVO;
import itn.let.org.service.OrgCharVO;
import itn.let.org.service.OrgChartManageService;
import itn.let.sec.ram.service.AuthorManageVO;
import itn.let.sec.ram.service.EgovAuthorManageService;
import itn.let.sec.rgm.service.EgovAuthorGroupService;
import itn.let.sym.ccm.cde.service.CmmnDetailCodeVO;
import itn.let.sym.mnu.mpm.service.MenuManageJTreeVO;
import itn.let.uss.umt.service.EgovUserManageService;
import itn.let.uss.umt.service.UserManageVO;

@Controller
public class OrgChartManageController {
	/** userManageService */
	@Resource(name = "userManageService")
	private EgovUserManageService userManageService;
	
	@Resource(name = "orgChartManageService")
	private OrgChartManageService orgChartManageService;
	
	@Resource(name = "egovLocInfoIdGnrService")
    private EgovIdGnrService idgenLocInfoId;
	
	@Resource(name = "egovAuthorManageService")
	private EgovAuthorManageService egovAuthorManageService;
	
	@Resource(name = "egovAuthorGroupService")
    private EgovAuthorGroupService egovAuthorGroupService;
	
	private String topLocNo = "1000000" ; //전역 최상위 매뉴번호 
	
	// 조직도 화면 
	@RequestMapping("/uss/orgChart/OrgChartManage.do")
	public String selectOrgChartInfo(LocVO locVO, ModelMap model, HttpServletResponse response) throws Exception {
		
		//권한조회
		AuthorManageVO authorManageVO = new AuthorManageVO();
		authorManageVO.setFirstIndex(0);
  		authorManageVO.setLastIndex(10);
  		authorManageVO.setRecordCountPerPage(10);
  		authorManageVO.setAuthorManageList(egovAuthorManageService.selectAuthorList(authorManageVO));
  		model.addAttribute("authorList", authorManageVO.getAuthorManageList());	
  		
  		//selectbox 미리 만들기
  		locVO.setTopLocNo(topLocNo); //최상위 매뉴번호
		List<LocVO> orgHiddenList = orgChartManageService.selectOrgChartListAjax(locVO);
		model.addAttribute("orgHiddenList", orgHiddenList);	
		return "/uss/orgchart/OrgChartManage";
	}
	
	/*부서 최초 트리 리스트 */
	@RequestMapping(value="/uss/orgChart/orgChartInitAjax.do")
	public void orgChartInitAjax(
			@ModelAttribute("menuManageVO") MenuManageJTreeVO menuManageVO
			, LocVO locVO
			, ModelMap model, HttpServletResponse response) throws Exception {
		
		ObjectMapper mapper = new ObjectMapper();
		response.setContentType("application/json");
		PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
		
		locVO.setTopLocNo(topLocNo); //최상위 매뉴번호
		List<LocVO> resultList = orgChartManageService.selectOrgChartListAjax(locVO);
		
		LocVO rootNode = new LocVO();
		rootNode.setParent("#");
		rootNode.setId(topLocNo);
		rootNode.setText("전체");
		resultList.add(0, rootNode);
		mapper.writeValue(out, resultList);
		out.flush();
	}
	
	@RequestMapping(value= {"/uss/orgChart/getOrgChartInitAjax_01.do" , "/uss/orgChart/getOrgChartInit01Ajax.do"})
	public ModelAndView getOrgChartInitAjax_01(
			@ModelAttribute("menuManageVO") MenuManageJTreeVO menuManageVO 
			, @ModelAttribute("searchVO") CmmnDetailCodeVO searchVO
			, ModelMap model, HttpServletResponse response) throws Exception{
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		OrgCharVO orgCharVO = new OrgCharVO();
		orgCharVO.setLocDepth(2);
		List<OrgCharVO> resultList = orgChartManageService.selectOrgChartDepthListAjax(orgCharVO);
		
		modelAndView.addObject("resultList", resultList);
		return modelAndView;
	}
	
	/*검색 select 02  리스트 */
	@RequestMapping(value= {"/uss/orgChart/getOrgChartInitAjax_02.do" , "/uss/orgChart/getOrgChartInit02Ajax.do"})
	public ModelAndView getOrgChartInitAjax_02(@ModelAttribute("menuManageVO") MenuManageJTreeVO menuManageVO, 
			@ModelAttribute("searchVO") CmmnDetailCodeVO searchVO,
			ModelMap model, HttpServletResponse response) throws Exception{
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		OrgCharVO orgCharVO = new OrgCharVO();
		orgCharVO.setLocDepth(3); //뎁스3인것만
		if(!searchVO.getSearchCondition_01().equals("")) {
			orgCharVO.setUpperLocNo(Integer.parseInt(searchVO.getSearchCondition_01()));
		}
		List<OrgCharVO> resultList = orgChartManageService.selectOrgChartDepthListAjax(orgCharVO);
		modelAndView.addObject("resultList", resultList);
		return modelAndView;
	}
	
	/*검색 select 03  리스트 */
	@RequestMapping(value= {"/uss/orgChart/getOrgChartInitAjax_03.do" , "/uss/orgChart/getOrgChartInit03Ajax.do"})
	public ModelAndView getOrgChartInitAjax_03(@ModelAttribute("menuManageVO") MenuManageJTreeVO menuManageVO, 
			@ModelAttribute("searchVO") CmmnDetailCodeVO searchVO,
			ModelMap model, HttpServletResponse response) throws Exception{
		ModelAndView modelAndView = new ModelAndView(); //부서별만 조회 가능
		modelAndView.setViewName("jsonView");
		OrgCharVO orgCharVO = new OrgCharVO();
		orgCharVO.setLocDepth(4); //뎁스3인것만
		if(!searchVO.getSearchCondition_02().equals("")) {
			orgCharVO.setUpperLocNo(Integer.parseInt(searchVO.getSearchCondition_02()));
		}
		List<OrgCharVO> resultList = orgChartManageService.selectOrgChartDepthListAjax(orgCharVO);
		modelAndView.addObject("resultList", resultList);
		return modelAndView;
	}
	
	// 부서별 직원 정보 보기
	@RequestMapping("/cop/selectUserListAjax.do")
	public ModelAndView selectStaffListAjax(
			@ModelAttribute("userManageVO") UserManageVO userManageVO
			, @ModelAttribute("orgCharVO") OrgCharVO orgCharVO, ModelMap model) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		if ((userManageVO.getPartIdx() != null) && (userManageVO.getPartIdx().equals("DEPT"))) {
			LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
			userManageVO.setPartIdx(loginVO.getOrgnztNo());
		}
		
		modelAndView.setViewName("jsonView");
		List<UserManageVO> userList = orgChartManageService.selectUserListAjax(userManageVO);
		model.addAttribute("userList", userList);
		
		LocVO  locVO = new LocVO();
		locVO.setLocNo(userManageVO.getPartIdx());
		locVO = orgChartManageService.selectLocCnVO(locVO);
		modelAndView.addObject("locVO", locVO);
		modelAndView.addObject("status", "success");
		
		return modelAndView;
	}
	
	// 직원 정보 조회하기
	@RequestMapping("/cop/selectUserInfoAjax.do")
	public ModelAndView selectUserInfoAjax(
			@ModelAttribute("userManageVO") UserManageVO userManageVO
			, ModelMap model) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		 try{
			 UserManageVO userInfo = orgChartManageService.selectUserInfoAjax(userManageVO);
			 //UserManageVO userInfo = orgChartManageService.selectUserLocInfoAjax(userManageVO);
			 modelAndView.addObject("userInfo", userInfo);
			 modelAndView.addObject("result", "success");
		 }catch(Exception e){
			 modelAndView.addObject("result", "fail");
	    }
		return modelAndView;
	}
	
	// 부서별 직원 수정하기
	@RequestMapping("/uss/orgChart/updateUserInfoAjax.do")
	public ModelAndView updateUserInfoAjax(
			@ModelAttribute("userManageVO") UserManageVO userManageVO
			, ModelMap model) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		 try{
			//업무사용자 수정시 히스토리 정보를 등록한다.
			//userManageService.insertUserHistory(userManageVO);
			//userManageService.updateUser(userManageVO);
			if(null== userManageVO.getLocInfoId() || "".equals(userManageVO.getLocInfoId())){
				
				String locInfoId = idgenLocInfoId.getNextStringId();
				userManageVO.setLocInfoId(locInfoId);
				userManageVO.setUserNm(userManageVO.getEmplyrNm());
				userManageService.insertLocInfo(userManageVO);
				
				modelAndView.addObject("I", "flag");
			}else {
				userManageService.updateLocInfo(userManageVO);
				modelAndView.addObject("U", "flag");
			}
			modelAndView.addObject("result", "success");
		 }catch(Exception e){
			 modelAndView.addObject("result", "fail");
	    }
		return modelAndView;
	}
	
	//부서별 직원 등록하기
	@RequestMapping("/cop/insertUserInfoAjax.do")
	public ModelAndView insertUserInfoAjax(
			@ModelAttribute("userManageVO") UserManageVO userManageVO
			, ModelMap model) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		 try{
			 userManageService.insertUser(userManageVO);
			 modelAndView.addObject("result", "success"); 
		 }catch(Exception e){
			 modelAndView.addObject("result", "fail");
	    }
		return modelAndView;
	}
	
	// 부서별 직원  삭제하기
	@RequestMapping("/cop/deleteUserInfoAjax.do")
	public ModelAndView deleteStaffInfoAjax(
			@ModelAttribute("userManageVO") UserManageVO userManageVO
			, @RequestParam("del") String[] del, ModelMap model) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		for(String id:del) {
			 try{
				 orgChartManageService.deleteUserInfoAjax(id);
				 modelAndView.addObject("result", "success");
			 }catch(Exception e){
				 modelAndView.addObject("result", "fail");
		    }
	   }
		return modelAndView;
	}
	
	// 조직도 화면 
	@RequestMapping("/uss/orgChart/OrgChartPopup.do")
	public String orgChartPopup(@ModelAttribute("locVO") LocVO locVO, 
			ModelMap model, 
			HttpServletResponse response) throws Exception {
		
		return "/uss/orgChart/OrgChartPopup";
	}
	
	/**
	 * 조직도 정보를 등록
	 *
	 * @param partInfVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/uss/orgChart/orgChartInsertAjax.do")
	public ModelAndView orgChartInsertAjax(@ModelAttribute("menuManageVO") MenuManageJTreeVO menuManageVO, 
			@ModelAttribute("cmmnDetailCodeVO") CmmnDetailCodeVO cmmnDetailCodeVO,
			ModelMap model, LocVO locVO ,
			@RequestParam("nodeIds") String[] nodeIds) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		LoginVO user  = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
		try {
			String compareStr = "";
			for(int i=1 ; i < 100 ; i++) {
				if(i<10) {
					compareStr = "0"+i;
				}
				if(!Arrays.asList(nodeIds).contains(compareStr)) {
					break;
				}
			}
			
			locVO.setLocNm("NEW DATA"); //임시
			locVO.setLocNo("9999999"); //임시
			
			String equiLevel = (locVO.getUpperMenuId()+"").replaceFirst("0" , "%");
			//List<LocVO> equiLocList = assetManageService.selectEquiLevelLocList(equiLevel);
			List<LocVO> equiLocList = orgChartManageService.selectEquiLevelLocList(equiLevel);
			
			
			ArrayList existLocNo = new ArrayList() ;  
			for(LocVO tempLocVO : equiLocList) {
				existLocNo.add(tempLocVO.getLocNo()) ;
			}
			int insertMenNo ;
			if(equiLocList.size() != 0){
				for(int i = 1 ; i < 100 ; i++){  //0~100까지 임의의 매뉴번호 생성후 이전 매뉴가 없는것을 조회
					insertMenNo = Integer.parseInt((locVO.getUpperMenuId()+"").replaceFirst("0" , i+"")) ;
					if(!existLocNo.contains(insertMenNo+"")){ //매뉴번호가 없으면
						locVO.setLocNo(insertMenNo+"");  
						break ;
					}
				}
			}else{
				insertMenNo = Integer.parseInt((locVO.getUpperMenuId()+"").replaceFirst("0" , "1"));
				locVO.setLocNo(insertMenNo+""); 
			}
			
			locVO.setUpperLocNo(locVO.getUpperMenuId()+"");
			locVO.setUseYn("Y");
			locVO.setFrstRegisterId(user.getId());
			locVO.setLocOrdr(nodeIds.length+1);
			locVO.setLocDepth(Integer.parseInt(locVO.getNodeDepth()));
			orgChartManageService.insertOrgChart(locVO);
			modelAndView.addObject("newMenuNo", locVO.getLocNo());
			modelAndView.addObject("status", "success");
			
		}catch (Exception e) {
			modelAndView.addObject("status", "fail");
			model.addAttribute("menuManageVO", cmmnDetailCodeVO);
		}
		return modelAndView;
	}
	
	/**
	 * 조직도 정보 이름 변경
	 *
	 * @param partInfVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uss/orgChart/orgChartNmUpdateAjax.do")
	public ModelAndView updateassetSubNmUpdateAjax(
			@ModelAttribute("menuManageVO") MenuManageJTreeVO menuManageVO, 
			@ModelAttribute("searchVO") CmmnDetailCodeVO searchVO,
			ModelMap model) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		try{
			LocVO locVO = new LocVO();
			locVO.setLocNm(menuManageVO.getMenuNm());
			locVO.setLocNo(menuManageVO.getMenuNo());
			//assetManageService.updateAssetLocNm(locVO);
			orgChartManageService.updateOrgChartNm(locVO);
			modelAndView.addObject("status", "success");
		}catch (Exception e) {
			modelAndView.addObject("status", "fail");
		}
		return modelAndView;
	}
	
	/**
	 * 부서 정보를 삭제한다.(트리구조에서)
	 *
	 * @param partInfVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@Transactional(rollbackFor = Exception.class)
	@RequestMapping(value = "/uss/orgChart/orgChartDeleteAjax.do")
	public ModelAndView orgChartDeleteAjax(@ModelAttribute("menuManageVO") MenuManageJTreeVO menuManageVO, 
			@ModelAttribute("cmmnDetailCodeVO") CmmnDetailCodeVO cmmnDetailCodeVO,
			LocVO locVO ,
			ModelMap model) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		try {
			locVO.setLocNo(menuManageVO.getMenuNo());
			orgChartManageService.deleteOrgChart(locVO);
			modelAndView.addObject("status", "success");
		}catch(Exception e) {
			modelAndView.addObject("status", "fail");
		}
		return modelAndView;
	}
	
	
	/**
	 * 부서 이동 한다.(트리구조에서)
	 */
	@Transactional(rollbackFor = Exception.class)
	@RequestMapping("/uss/itsm/asset/AssetMoveAjax.do")
	public ModelAndView asetMoveAjax(
			@ModelAttribute("menuManageVO") MenuManageJTreeVO menuManageVO,
			@ModelAttribute("cmmnDetailCodeVO") CmmnDetailCodeVO cmmnDetailCodeVO,
			LocVO locVO ,
			ModelMap model) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		LoginVO user  = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
		try{
			locVO.setLocNo(menuManageVO.getMenuNo());
			locVO.setUpperLocNo(menuManageVO.getUpperMenuId());
			locVO.setLocOrdr(locVO.getSort());
			orgChartManageService.updateLocDate(locVO);
			orgChartManageService.resortLoc(locVO);
			modelAndView.addObject("status", "success");
		}catch (Exception e) {
			modelAndView.addObject("status", "fail");
		}
		return modelAndView;
	}
	
	
	// 조직도 화면 (사용자)
	@RequestMapping("/web/cop/org/selectOrgList.do")
	public String selectOrgList(LocVO locVO, ModelMap model, HttpServletResponse response) throws Exception {
		
  		//selectbox 미리 만들기
  		locVO.setTopLocNo(topLocNo); //최상위 매뉴번호
		List<LocVO> orgList = orgChartManageService.selectOrgChartListAjax(locVO);
		
		List<LocVO> headOrgList = new ArrayList<>();
		{
			headOrgList.add(orgList.get(0)) ;
			headOrgList.add(orgList.get(1)) ;
			headOrgList.add(orgList.get(2)) ;
		}
		model.addAttribute("headOrgList", headOrgList);
		{
			orgList.remove(0);
			orgList.remove(0);
			orgList.remove(0);
		}
		model.addAttribute("orgSubList", orgList);	
		return "/web/cop/org/selectOrgList";
	}
	
	
	// 조직도 상세 (사용자)
	@RequestMapping("/web/cop/org/selectOrgDetail.do")
	public String selectOrgDetail(LocVO locVO, ModelMap model, UserManageVO userManageVO, HttpServletResponse response) throws Exception {
		
		List<UserManageVO> userList = orgChartManageService.selectUserListAjax(userManageVO);
		locVO.setLocNo(userManageVO.getPartIdx());
		LocVO resultLocVO = orgChartManageService.selectLocCnVO(locVO);
		model.addAttribute("userList", userList);	
		model.addAttribute("locVO", resultLocVO);	
		
		List<LocVO> locPathList  = orgChartManageService.selectLocPath(locVO);
		model.addAttribute("locPathList", locPathList);	
		/*OrgCharVO orgCharVO = new OrgCharVO();
		orgCharVO.setLocDepth(2);
		List<OrgCharVO> resultList = orgChartManageService.selectOrgChartDepthListAjax(orgCharVO);*/
		
		
		return "/web/cop/org/selectOrgDetail";
	}
		
	
	// 부서 업무 저장하기
	@RequestMapping("/uss/orgChart/updateLocCnSaveAjax.do")
	public ModelAndView updateLocCnSaveAjax(
			@ModelAttribute("userManageVO") UserManageVO userManageVO, LocVO locVO
			, ModelMap model) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		 try{
			//업무사용자 수정시 히스토리 정보를 등록한다.
			/*userManageService.insertUserHistory(userManageVO);
			userManageService.updateUser(userManageVO);*/
			 //orgChartManageService.selectOrgChartListAjax(locVO);
			 orgChartManageService.updateLocCnSaveAjax(locVO);
			 modelAndView.addObject("result", "success");
		 }catch(Exception e){
			 modelAndView.addObject("result", "fail");
	    }
		return modelAndView;
	}
	
	
	// 직원  삭제하기
	@RequestMapping("/cop/deleteUserInfoLocAjax.do")
	public ModelAndView deleteUserInfoLocAjax(
			@ModelAttribute("userManageVO") UserManageVO userManageVO,
			ModelMap model) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		 try{
			 orgChartManageService.deleteUserInfoLocAjax(userManageVO.getEmplyrId());
			 modelAndView.addObject("result", "success");
		 }catch(Exception e){
			 modelAndView.addObject("result", "fail");
		 } 
		return modelAndView;
	}
		
		
	
	
}
