package egovframework.rte.cvpl.web;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;

import net.sourceforge.ajaxtags.xml.AjaxXmlBuilder;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springmodules.validation.commons.DefaultBeanValidator;

import egovframework.rte.cvpl.common.EgovCvplCmmn;
import egovframework.rte.cvpl.common.EgovCvplSessionAuth;
import egovframework.rte.cvpl.service.CvplCnsltVO;
import egovframework.rte.cvpl.service.CvplSearchVO;
import egovframework.rte.cvpl.service.EgovCvplCnsltService;
import egovframework.rte.cvpl.util.EgovWebServiceClientRegisterCvpl;
import egovframework.rte.cvpl.web.view.CvplAjaxXmlView;
import egovframework.rte.fdl.property.EgovPropertyService;
import egovframework.rte.fdl.security.userdetails.util.EgovUserDetailsHelper;
import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;



/**
 * @Class Name : EgovCvplCnsltController.java
 * @Description : EgovCvplCnslt Controller class
 * @Modification Information
 * @
 * @  수정일         수정자                   수정내용
 * @ -------    --------    ---------------------------
 * @ 2009.03.05    천종덕          최초 생성
 *
 *  @author 실행환경 개발팀 천종덕
 *  @since 2009.03.05
 *  @version 1.0
 *  @see
 *  
 *  Copyright (C) 2009 by MOPAS  All right reserved.
 */

@Controller
@SessionAttributes(types=CvplCnsltVO.class)
public class EgovCvplCnsltController {

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

	/** EgovCvplCnsltService */
    @Resource(name = "cvplCnsltService")
    private EgovCvplCnsltService cvplCnsltService;
    
    /** EgovPropertyService */
    @Resource(name = "propertiesService")
    protected EgovPropertyService propertiesService;
	
    /** Validator */
    @Resource(name = "beanValidator")
	protected DefaultBeanValidator beanValidator;

    /** egovCvplCmmn */
    @Resource(name="egovCvplCmmn")
    protected EgovCvplCmmn egovCvplCmmn;

	/** EgovWebServiceClientRegisterCvpl */
    @Resource(name = "egovWebServiceClientRegisterCvpl")
    private EgovWebServiceClientRegisterCvpl egovWebServiceClientRegisterCvpl;
    
	/**
	 * 글 목록을 조회한다. (pageing)
	 * @param searchVO - 조회할 정보가 담긴 CvplSearchVO
	 * @return "/cvpl/egovCvplCnsltList"
	 * @exception Exception
	 */                 
    @RequestMapping(value="/cvpl/egovCvplCnsltList.do")
    public String selectCvplCnsltList(@ModelAttribute("searchVO") CvplSearchVO searchVO, 
    		ModelMap model)
            throws Exception {
    	
    	/** EgovPropertyService */
    	searchVO.setPageUnit(propertiesService.getInt("pageUnit"));
    	searchVO.setPageSize(propertiesService.getInt("pageSize"));
    	
    	/** pageing */
    	PaginationInfo paginationInfo = new PaginationInfo();
		paginationInfo.setCurrentPageNo(searchVO.getPageIndex());
		paginationInfo.setRecordCountPerPage(searchVO.getPageUnit());
		paginationInfo.setPageSize(searchVO.getPageSize());
		
    	/* Session */
    	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	

    	/** 일반 사용자의 경우 비공개 민원은 보여주지 않는다. */
    	if(egovCvplSessionAuth.getIsUser()) {
    		searchVO.setSearchSubKeyword(propertiesService.getString("cvplOthbcValueOpen"));
    	}
		searchVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
		searchVO.setLastIndex(paginationInfo.getLastRecordIndex());
		searchVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
		
        List cvplCnsltList = cvplCnsltService.selectCvplCnsltList(searchVO);
        model.addAttribute("resultList", cvplCnsltList);
        
        int totCnt = cvplCnsltService.selectCvplCnsltListTotCnt(searchVO);
		paginationInfo.setTotalRecordCount(totCnt);
        model.addAttribute("paginationInfo", paginationInfo);
        
        /** 공백이 아닌 경우, 검색어의 중복을 체크한다. */
        String searchKeyword = searchVO.getSearchKeyword();
        if (!searchKeyword.equals("")) {
	        String dupSrchKeyword = cvplCnsltService.checkDupSearchKeywordList(searchKeyword);
	        
	        if (!searchKeyword.equals(dupSrchKeyword)) {
	            /** 검색어를 등록한다. */
	        	cvplCnsltService.insertSearchKeywordList(searchKeyword);
	        }
        }
        
        model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

        return "/cvpl/EgovCvplCnsltList";
    } 
    
	/**
	 * 민원등록화면을 조회한다.
	 * @param searchVO - 조회할 정보가 담긴 CvplSearchVO
	 * @return "/cvpl/EgovCvplCnsltRegister"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/addCvplCnsltView.do")
    public String addCvplCnsltView(
            @ModelAttribute("searchVO") CvplSearchVO searchVO, Model model)
            throws Exception {

    	/* Session */
    	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	

    	/** user Name process*/
        CvplCnsltVO cvplCnsltVO = new CvplCnsltVO();
    	cvplCnsltVO.setUserName(egovCvplSessionAuth.getUserName());
    	
        model.addAttribute("cvplCnsltVO", cvplCnsltVO);
        /** 민원공개여부 공통코드 리스트를 가져온다. */
		model.addAttribute("cvplOthbcCategory", egovCvplCmmn.getCmmnCd(propertiesService.getString("cvplOthbcCode")));
        model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

        return "/cvpl/EgovCvplCnsltRegister";
    }
    
	/**
	 * 민원답변등록화면을 조회한다.
	 * @param searchVO - 조회할 정보가 담긴 CvplSearchVO
	 * @return "/cvpl/EgovCvplCnsltRegisterAnswer"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/insertAnswerCvplCnsltView.do")
    public String insertAnswerCvplCnsltView(
            @RequestParam("selectedId") String id ,
            @ModelAttribute("searchVO") CvplSearchVO searchVO, Model model)
            throws Exception {

    	/* Session */
    	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	

    	/** user Name process*/
        CvplCnsltVO cvplCnsltVO = new CvplCnsltVO();
        cvplCnsltVO.setCvplNo(id);
        cvplCnsltVO = selectCvplCnslt(cvplCnsltVO, searchVO);
    	cvplCnsltVO.setAnswerUserName(egovCvplSessionAuth.getUserName());
    	
        model.addAttribute(cvplCnsltVO);
        model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

       return "/cvpl/EgovCvplCnsltRegisterAnswer";
    }
    
	/**
	 * 민원을 등록한다.
	 * @param cvplCnsltVO - 등록할 정보가 담긴 CvplCnsltVO
	 * @return "/cvpl/egovCvplCnsltList"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/addCvplCnslt.do")
    public String addCvplCnslt(
    		final MultipartHttpServletRequest multiRequest,
            @ModelAttribute("searchVO") CvplSearchVO searchVO, 
            CvplCnsltVO cvplCnsltVO,
            BindingResult bindingResult, Model model, SessionStatus status)
            throws Exception {
    	
    	/* Session */
    	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	

    	/** userId process*/
    	cvplCnsltVO.setUserId(egovCvplSessionAuth.getUserId());
    	
    	/** admnstmachCode process*/
    	cvplCnsltVO.setAdmnstmachCode(propertiesService.getString("myAdmnstmachValue"));
    	
    	/** From validate process*/
    	beanValidator.validate(cvplCnsltVO, bindingResult);
    	
    	if (bindingResult.hasErrors()) {
    		model.addAttribute("cvplCnsltVO", cvplCnsltVO);
            /** 민원공개여부 공통코드 리스트를 가져온다. */
    		model.addAttribute("cvplOthbcCategory", egovCvplCmmn.getCmmnCd(propertiesService.getString("cvplOthbcCode")));
            model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

			return "/cvpl/EgovCvplCnsltRegister";
    	}

    	/** 파일 처리 */
    	final Map<String, MultipartFile> files = multiRequest.getFileMap();

		/** 디렉토리 생성 */
		File saveFolder = new File(propertiesService.getString("fileDir"));
		boolean isDir = false;
		if (!saveFolder.exists() || saveFolder.isFile()) {
			isDir = saveFolder.mkdirs();
		} else {
			isDir = true;
		}

		if (!isDir) {
			log.debug("Fail Create folder!!");
    		model.addAttribute("cvplCnsltVO", cvplCnsltVO);
            /** 민원공개여부 공통코드 리스트를 가져온다. */
    		model.addAttribute("cvplOthbcCategory", egovCvplCmmn.getCmmnCd(propertiesService.getString("cvplOthbcCode")));
            model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

			return "/cvpl/EgovCvplCnsltRegister";
		}
		
		Iterator<Entry<String, MultipartFile>> itr = files.entrySet().iterator();
		MultipartFile file;
		String filePath = "";
		int fileKey = 0;
		
		while (itr.hasNext()) {
			Entry<String, MultipartFile> entry = itr.next();
			
			file = entry.getValue();
			if (!"".equals(file.getOriginalFilename())) {
				filePath = propertiesService.getString("filePath") + file.getOriginalFilename();
				file.transferTo(new File(filePath));
			}

			if(fileKey == 0 && !"".equals(file.getOriginalFilename())) {
				cvplCnsltVO.setCvplAtch1(file.getOriginalFilename());
			}
			if(fileKey == 1 && !"".equals(file.getOriginalFilename())) {
				cvplCnsltVO.setCvplAtch2(file.getOriginalFilename());
			}
			fileKey++;
		}
        
        cvplCnsltService.insertCvplCnslt(cvplCnsltVO);
        status.setComplete();
        return "forward:/cvpl/egovCvplCnsltList.do";
    }
    
	/**
	 * 민원답변을 등록한다.
	 * @param cvplCnsltVO - 등록할 정보가 담긴 CvplCnsltVO
	 * @return "/cvpl/EgovCvplCnsltView"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/insertAnswerCvplCnslt.do")
    public String insertAnswerCvplCnslt(
    		final MultipartHttpServletRequest multiRequest,
            @ModelAttribute("searchVO") CvplSearchVO searchVO, 
            CvplCnsltVO cvplCnsltVO,
            Model model, SessionStatus status)
            throws Exception {
    	
    	/* Session */
    	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	

    	/** AnswerUserId process*/
    	cvplCnsltVO.setAnswerUserId(egovCvplSessionAuth.getUserId());
    	
    	/** 파일 처리 */
    	final Map<String, MultipartFile> files = multiRequest.getFileMap();

		/** 디렉토리 생성 */
		File saveFolder = new File(propertiesService.getString("fileDir"));
		boolean isDir = false;
		if (!saveFolder.exists() || saveFolder.isFile()) {
			isDir = saveFolder.mkdirs();
		} else {
			isDir = true;
		}

		if (!isDir) {
			log.debug("Fail Create folder!!");
	        model.addAttribute(selectCvplCnslt(cvplCnsltVO, searchVO));
            model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

			return "/cvpl/EgovCvplCnsltView";
		}
		
		Iterator<Entry<String, MultipartFile>> itr = files.entrySet().iterator();
		MultipartFile file;
		String filePath = "";
		int fileKey = 0;
		
		while (itr.hasNext()) {
			Entry<String, MultipartFile> entry = itr.next();
			
			file = entry.getValue();
			if (!"".equals(file.getOriginalFilename())) {
				filePath = propertiesService.getString("filePath") + file.getOriginalFilename();
				file.transferTo(new File(filePath));
			}

			if(fileKey == 0 && !"".equals(file.getOriginalFilename())) {
				cvplCnsltVO.setAnswerAtch1(file.getOriginalFilename());
			}
			if(fileKey == 1 && !"".equals(file.getOriginalFilename())) {
				cvplCnsltVO.setAnswerAtch2(file.getOriginalFilename());
			}
			fileKey++;
		}
        
        cvplCnsltService.insertAnswerCvplCnslt(cvplCnsltVO);
        status.setComplete();
        model.addAttribute(selectCvplCnslt(cvplCnsltVO, searchVO));
        model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

        return "/cvpl/EgovCvplCnsltView";
    }
    
	/**
	 * 민원수정화면을 조회한다.
	 * @param searchVO - 조회할 정보가 담긴 CvplSearchVO
	 * @return "/cvpl/EgovCvplCnsltUpdate"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/updateCvplCnsltView.do")
    public String updateCvplCnsltView(
            @RequestParam("selectedId") String id ,
            @ModelAttribute("searchVO") CvplSearchVO searchVO, Model model)
            throws Exception {
        CvplCnsltVO cvplCnsltVO = new CvplCnsltVO();
        cvplCnsltVO.setCvplNo(id);
        model.addAttribute(selectCvplCnslt(cvplCnsltVO, searchVO));
        /** 민원공개여부 공통코드 리스트를 가져온다. */
		model.addAttribute("cvplOthbcCategory", egovCvplCmmn.getCmmnCd(propertiesService.getString("cvplOthbcCode")));
    	/* Session */
    	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	
        model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

        return "/cvpl/EgovCvplCnsltUpdate";
    }

	/**
	 * 민원답변수정화면을 조회한다.
	 * @param searchVO - 조회할 정보가 담긴 CvplSearchVO
	 * @return "/cvpl/EgovCvplCnsltUpdateAnswer"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/updateAnswerCvplCnsltView.do")
    public String updateAnswerCvplCnsltView(
            @RequestParam("selectedId") String id ,
            @ModelAttribute("searchVO") CvplSearchVO searchVO, Model model)
            throws Exception {
        CvplCnsltVO cvplCnsltVO = new CvplCnsltVO();
        cvplCnsltVO.setCvplNo(id);
        model.addAttribute(selectCvplCnslt(cvplCnsltVO, searchVO));
    	/* Session */
    	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	
        model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

        return "/cvpl/EgovCvplCnsltUpdateAnswer";
    }

	/**
	 * 민원 한건을 조회한다.
	 * @param searchVO - 조회할 정보가 담긴 CvplSearchVO
	 * @return "CvplCnsltVO cvplCnsltVO"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/selectCvplCnslt.do")
    public @ModelAttribute("cvplCnsltVO")
    CvplCnsltVO selectCvplCnslt(
            CvplCnsltVO cvplCnsltVO,
            @ModelAttribute("searchVO") CvplSearchVO searchVO) throws Exception {
        return cvplCnsltService.selectCvplCnslt(cvplCnsltVO);
    }

	/**
	 * 민원을 수정한다.
	 * @param cvplCnsltVO - 수정할 정보가 담긴 CvplCnsltVO
	 * @return "/cvpl/egovCvplCnsltList"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/updateCvplCnslt.do")
    public String updateCvplCnslt(
    		final MultipartHttpServletRequest multiRequest,
    		@RequestParam("fileYN") String fileYN,
            @ModelAttribute("searchVO") CvplSearchVO searchVO, 
            CvplCnsltVO cvplCnsltVO,
            BindingResult bindingResult, Model model, SessionStatus status)
            throws Exception {

    	/** From validate process*/
    	beanValidator.validate(cvplCnsltVO, bindingResult);
    	
    	if (bindingResult.hasErrors()) {
    		model.addAttribute("cvplCnsltVO", cvplCnsltVO);
            /** 민원공개여부 공통코드 리스트를 가져온다. */
    		model.addAttribute("cvplOthbcCategory", egovCvplCmmn.getCmmnCd(propertiesService.getString("cvplOthbcCode")));
        	/* Session */
        	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	
            model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

			return "/cvpl/EgovCvplCnsltUpdate";
    	}

    	/** 파일을 새로 첨부했다면 */
    	if(fileYN.equals("Y")) {
	    	/** 파일 처리 */
	    	final Map<String, MultipartFile> files = multiRequest.getFileMap();
	
			/** 디렉토리 생성 */
			File saveFolder = new File(propertiesService.getString("fileDir"));
			boolean isDir = false;
			if (!saveFolder.exists() || saveFolder.isFile()) {
				isDir = saveFolder.mkdirs();
			} else {
				isDir = true;
			}

			if (!isDir) {
				log.debug("Fail Create folder!!");
	    		model.addAttribute("cvplCnsltVO", cvplCnsltVO);
	            /** 민원공개여부 공통코드 리스트를 가져온다. */
	    		model.addAttribute("cvplOthbcCategory", egovCvplCmmn.getCmmnCd(propertiesService.getString("cvplOthbcCode")));
	        	/* Session */
	        	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	
	            model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

				return "/cvpl/EgovCvplCnsltUpdate";
			}
			
			Iterator<Entry<String, MultipartFile>> itr = files.entrySet().iterator();
			MultipartFile file;
			String filePath = "";
			int fileKey = 0;
			
			while (itr.hasNext()) {
				Entry<String, MultipartFile> entry = itr.next();
				
				file = entry.getValue();
				if (!"".equals(file.getOriginalFilename())) {
					filePath = propertiesService.getString("filePath") + file.getOriginalFilename();
					file.transferTo(new File(filePath));
				}
	
				if(fileKey == 0 && !"".equals(file.getOriginalFilename())) {
					cvplCnsltVO.setCvplAtch1(file.getOriginalFilename());
				}
				if(fileKey == 1 && !"".equals(file.getOriginalFilename())) {
					cvplCnsltVO.setCvplAtch2(file.getOriginalFilename());
				}
				fileKey++;
			}
    	}
    	
        cvplCnsltService.updateCvplCnslt(cvplCnsltVO);
        status.setComplete();
        return "forward:/cvpl/egovCvplCnsltList.do";
    }
    
	/**
	 * 민원답변을 수정한다.
	 * @param cvplCnsltVO - 수정할 정보가 담긴 CvplCnsltVO
	 * @return "/cvpl/EgovCvplCnsltView"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/updateAnswerCvplCnslt.do")
    public String updateAnswerCvplCnslt(
    		final MultipartHttpServletRequest multiRequest,
    		@RequestParam("fileYN") String fileYN,
            @ModelAttribute("searchVO") CvplSearchVO searchVO, 
            CvplCnsltVO cvplCnsltVO,
            Model model, SessionStatus status)
            throws Exception {

    	/** 파일을 새로 첨부했다면 */
    	if(fileYN.equals("Y")) {
	    	/** 파일 처리 */
	    	final Map<String, MultipartFile> files = multiRequest.getFileMap();
	
			/** 디렉토리 생성 */
			File saveFolder = new File(propertiesService.getString("fileDir"));
			boolean isDir = false;
			if (!saveFolder.exists() || saveFolder.isFile()) {
				isDir = saveFolder.mkdirs();
			} else {
				isDir = true;
			}

			if (!isDir) {
				log.debug("Fail Create folder!!");
		        model.addAttribute(selectCvplCnslt(cvplCnsltVO, searchVO));
	        	/* Session */
	        	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	
	            model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

				return "/cvpl/EgovCvplCnsltView";
			}
			
			Iterator<Entry<String, MultipartFile>> itr = files.entrySet().iterator();
			MultipartFile file;
			String filePath = "";
			int fileKey = 0;
			
			while (itr.hasNext()) {
				Entry<String, MultipartFile> entry = itr.next();
				
				file = entry.getValue();
				if (!"".equals(file.getOriginalFilename())) {
					filePath = propertiesService.getString("filePath") + file.getOriginalFilename();
					file.transferTo(new File(filePath));
				}
	
				if(fileKey == 0 && !"".equals(file.getOriginalFilename())) {
					cvplCnsltVO.setAnswerAtch1(file.getOriginalFilename());
				}
				if(fileKey == 1 && !"".equals(file.getOriginalFilename())) {
					cvplCnsltVO.setAnswerAtch2(file.getOriginalFilename());
				}
				fileKey++;
			}
    	}
    	
        cvplCnsltService.updateAnswerCvplCnslt(cvplCnsltVO);
        status.setComplete();
        model.addAttribute(selectCvplCnslt(cvplCnsltVO, searchVO));
    	/* Session */
    	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	
        model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

       return "/cvpl/EgovCvplCnsltView";
    }
    
	/**
	 * 민원을 삭제한다.
	 * @param cvplCnsltVO - 삭제할 정보가 담긴 CvplCnsltVO
	 * @return "/cvpl/egovCvplCnsltList"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/deleteCvplCnslt.do")
    public String deleteCvplCnslt(
            CvplCnsltVO cvplCnsltVO,
            @ModelAttribute("searchVO") CvplSearchVO searchVO, SessionStatus status)
            throws Exception {
        cvplCnsltService.deleteCvplCnslt(cvplCnsltVO);
        status.setComplete();
        return "forward:/cvpl/egovCvplCnsltList.do";
    }

	/**
	 * 민원답변을 삭제한다.
	 * @param cvplCnsltVO - 삭제할 정보가 담긴 CvplCnsltVO
	 * @return "/cvpl/EgovCvplCnsltView"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/deleteAnswerCvplCnslt.do")
    public String deleteAnswerCvplCnslt(
            CvplCnsltVO cvplCnsltVO,
            @ModelAttribute("searchVO") CvplSearchVO searchVO, SessionStatus status, Model model)
            throws Exception {
        cvplCnsltService.deleteAnswerCvplCnslt(cvplCnsltVO);
        status.setComplete();
        model.addAttribute(selectCvplCnslt(cvplCnsltVO, searchVO));
    	/* Session */
    	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	
        model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

        return "/cvpl/EgovCvplCnsltView";
    }

	/**
	 * 민원 상세보기 화면을 조회한다.
	 * @param searchVO - 조회할 정보가 담긴 CvplSearchVO
	 * @return "/cvpl/EgovCvplCnsltView"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/viewCvplCnsltView.do")
    public String viewCvplCnsltView(
            @RequestParam("selectedId") String id ,
            @ModelAttribute("searchVO") CvplSearchVO searchVO, Model model)
            throws Exception {
        CvplCnsltVO cvplCnsltVO = new CvplCnsltVO();
        cvplCnsltVO.setCvplNo(id);
        model.addAttribute(selectCvplCnslt(cvplCnsltVO, searchVO));
    	/* Session */
    	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	
        model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

        return "/cvpl/EgovCvplCnsltView";
    }

    /**
	 * 검색어의 자동완성기능을 구현한다.
	 * @param searchKeyword - 자동완성기능을 사용할 문자
	 * @return "/cvpl/egovCvplCnsltList"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/egovCvplCnsltSearchAjax.do")
	protected ModelAndView handle(@RequestParam("searchKeyword") String searchKeyword) 
    			throws Exception {
				
		ModelAndView model = new ModelAndView(new CvplAjaxXmlView());
		List<String> searchKeywordList = cvplCnsltService.selectSearchKeywordList(searchKeyword);
		
		AjaxXmlBuilder ajaxXmlBuilder = new AjaxXmlBuilder();
		 
		for(String srchkeyword:searchKeywordList){
			ajaxXmlBuilder.addItem(srchkeyword, srchkeyword, false);			
		}

		model.addObject("ajaxXml",ajaxXmlBuilder.toString());
		return model;
	}

    /**
	 * 엑셀파일 목록을 조회한다. 
	 * @param searchVO - 조회할 정보가 담긴 CvplSearchVO
	 * @return "cvplCnsltExcelView"
	 * @exception Exception
	 */                 
    @RequestMapping(value="/cvpl/excelDownCvplCnsltList.do")
    public ModelAndView excelDownCvplCnsltList(@ModelAttribute("searchVO") CvplSearchVO searchVO)
            throws Exception {
    	
        List cvplCnsltList = cvplCnsltService.excelDownCvplCnsltList(searchVO);
        
    	/* Session */
    	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	

    	/** 일반 사용자의 경우 비공개 민원은 보여주지 않는다. */
    	if(egovCvplSessionAuth.getIsUser()) {
    		searchVO.setSearchSubKeyword(propertiesService.getString("cvplOthbcValueOpen"));
    	}
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("cvplCnslt", cvplCnsltList);

        return new ModelAndView("cvplCnsltExcelView", "cvplCnsltMap", map);
    } 
    
	/**
	 * 나의민원 목록을 조회한다. (pageing)
	 * @param searchVO - 조회할 정보가 담긴 CvplSearchVO
	 * @return "/cvpl/egovCvplCnsltMyList"
	 * @exception Exception
	 */                 
    @RequestMapping(value="/cvpl/egovCvplCnsltMyList.do")
    public String selectCvplCnsltMyList(@ModelAttribute("searchVO") CvplSearchVO searchVO, 
    		ModelMap model)
            throws Exception {
    	
    	/** EgovPropertyService */
    	searchVO.setPageUnit(propertiesService.getInt("pageUnit"));
    	searchVO.setPageSize(propertiesService.getInt("pageSize"));
    	
    	/** pageing */
    	PaginationInfo paginationInfo = new PaginationInfo();
		paginationInfo.setCurrentPageNo(searchVO.getPageIndex());
		paginationInfo.setRecordCountPerPage(searchVO.getPageUnit());
		paginationInfo.setPageSize(searchVO.getPageSize());
		
    	/* Session */
    	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	

		/** 나의 민원 조회키 */
		searchVO.setSearchSubKeyword(egovCvplSessionAuth.getUserId());
		searchVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
		searchVO.setLastIndex(paginationInfo.getLastRecordIndex());
		searchVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
		
        List cvplCnsltList = cvplCnsltService.selectCvplCnsltMyList(searchVO);
        model.addAttribute("resultList", cvplCnsltList);
        
        int totCnt = cvplCnsltService.selectCvplCnsltListTotCnt(searchVO);
		paginationInfo.setTotalRecordCount(totCnt);
        model.addAttribute("paginationInfo", paginationInfo);
        
        /** 공백이 아닌 경우, 검색어의 중복을 체크한다. */
        String searchKeyword = searchVO.getSearchKeyword();
        if (!searchKeyword.equals("")) {
	        String dupSrchKeyword = cvplCnsltService.checkDupSearchKeywordList(searchKeyword);
	        
	        if (!searchKeyword.equals(dupSrchKeyword)) {
	            /** 검색어를 등록한다. */
	        	cvplCnsltService.insertSearchKeywordList(searchKeyword);
	        }
        }
        
        model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

        return "/cvpl/EgovCvplCnsltMyList";
    } 
    
	/**
	 * 나의민원 상세보기 화면을 조회한다.
	 * @param searchVO - 조회할 정보가 담긴 CvplSearchVO
	 * @return "/cvpl/EgovCvplCnsltMyView"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/viewCvplCnsltMyView.do")
    public String viewCvplCnsltMyView(
            @RequestParam("selectedId") String id ,
            @ModelAttribute("searchVO") CvplSearchVO searchVO, Model model)
            throws Exception {
        CvplCnsltVO cvplCnsltVO = new CvplCnsltVO();
        cvplCnsltVO.setCvplNo(id);
        model.addAttribute(selectCvplCnslt(cvplCnsltVO, searchVO));
    	/* Session */
    	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	
        model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

        return "/cvpl/EgovCvplCnsltMyView";
    }

	/**
	 * 나의민원 수정화면을 조회한다.
	 * @param searchVO - 조회할 정보가 담긴 CvplSearchVO
	 * @return "/cvpl/EgovCvplCnsltMyUpdate"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/updateCvplCnsltMyView.do")
    public String updateCvplCnsltMyView(
            @RequestParam("selectedId") String id ,
            @ModelAttribute("searchVO") CvplSearchVO searchVO, Model model)
            throws Exception {
        CvplCnsltVO cvplCnsltVO = new CvplCnsltVO();
        cvplCnsltVO.setCvplNo(id);
        model.addAttribute(selectCvplCnslt(cvplCnsltVO, searchVO));
        /** 민원공개여부 공통코드 리스트를 가져온다. */
		model.addAttribute("cvplOthbcCategory", egovCvplCmmn.getCmmnCd(propertiesService.getString("cvplOthbcCode")));
    	/* Session */
    	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	
        model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

        return "/cvpl/EgovCvplCnsltMyUpdate";
    }

	/**
	 * 나의민원을 수정한다.
	 * @param cvplCnsltVO - 수정할 정보가 담긴 CvplCnsltVO
	 * @return "/cvpl/egovCvplCnsltMyList"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/updateCvplCnsltMy.do")
    public String updateCvplCnsltMy(
    		final MultipartHttpServletRequest multiRequest,
    		@RequestParam("fileYN") String fileYN,
            @ModelAttribute("searchVO") CvplSearchVO searchVO, 
            CvplCnsltVO cvplCnsltVO,
            BindingResult bindingResult, Model model, SessionStatus status)
            throws Exception {

    	/** From validate process*/
    	beanValidator.validate(cvplCnsltVO, bindingResult);
    	
    	if (bindingResult.hasErrors()) {
    		model.addAttribute("cvplCnsltVO", cvplCnsltVO);
            /** 민원공개여부 공통코드 리스트를 가져온다. */
    		model.addAttribute("cvplOthbcCategory", egovCvplCmmn.getCmmnCd(propertiesService.getString("cvplOthbcCode")));
        	/* Session */
        	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	
            model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

			return "/cvpl/EgovCvplCnsltUpdate";
    	}

    	/** 파일을 새로 첨부했다면 */
    	if(fileYN.equals("Y")) {
	    	/** 파일 처리 */
	    	final Map<String, MultipartFile> files = multiRequest.getFileMap();
	
			/** 디렉토리 생성 */
			File saveFolder = new File(propertiesService.getString("fileDir"));
			boolean isDir = false;
			if (!saveFolder.exists() || saveFolder.isFile()) {
				isDir = saveFolder.mkdirs();
			} else {
				isDir = true;
			}

			if (!isDir) {
				log.debug("Fail Create folder!!");
	    		model.addAttribute("cvplCnsltVO", cvplCnsltVO);
	            /** 민원공개여부 공통코드 리스트를 가져온다. */
	    		model.addAttribute("cvplOthbcCategory", egovCvplCmmn.getCmmnCd(propertiesService.getString("cvplOthbcCode")));
	        	/* Session */
	        	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	
	            model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

				return "/cvpl/EgovCvplCnsltUpdate";
			}
			
			Iterator<Entry<String, MultipartFile>> itr = files.entrySet().iterator();
			MultipartFile file;
			String filePath = "";
			int fileKey = 0;
			
			while (itr.hasNext()) {
				Entry<String, MultipartFile> entry = itr.next();
				
				file = entry.getValue();
				if (!"".equals(file.getOriginalFilename())) {
					filePath = propertiesService.getString("filePath") + file.getOriginalFilename();
					file.transferTo(new File(filePath));
				}
	
				if(fileKey == 0 && !"".equals(file.getOriginalFilename())) {
					cvplCnsltVO.setCvplAtch1(file.getOriginalFilename());
				}
				if(fileKey == 1 && !"".equals(file.getOriginalFilename())) {
					cvplCnsltVO.setCvplAtch2(file.getOriginalFilename());
				}
				fileKey++;
			}
    	}
    	
        cvplCnsltService.updateCvplCnslt(cvplCnsltVO);
        status.setComplete();
        return "forward:/cvpl/egovCvplCnsltMyList.do";
    }
    
	/**
	 * 나의민원을 삭제한다.
	 * @param cvplCnsltVO - 삭제할 정보가 담긴 CvplCnsltVO
	 * @return "/cvpl/egovCvplCnsltMyList"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/deleteCvplCnsltMy.do")
    public String deleteCvplCnsltMy(
            CvplCnsltVO cvplCnsltVO,
            @ModelAttribute("searchVO") CvplSearchVO searchVO, SessionStatus status)
            throws Exception {
        cvplCnsltService.deleteCvplCnslt(cvplCnsltVO);
        status.setComplete();
        return "forward:/cvpl/egovCvplCnsltMyList.do";
    }

    /**
	 * 나의민원 엑셀파일 목록을 조회한다. 
	 * @param searchVO - 조회할 정보가 담긴 CvplSearchVO
	 * @return "cvplCnsltMyExcelView"
	 * @exception Exception
	 */                 
    @RequestMapping(value="/cvpl/excelDownCvplCnsltMyList.do")
    public ModelAndView excelDownCvplCnsltMyList(@ModelAttribute("searchVO") CvplSearchVO searchVO)
            throws Exception {
    	
    	/* Session */
    	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	

		/** 나의 민원 조회키 */
		searchVO.setSearchSubKeyword(egovCvplSessionAuth.getUserId());
        List cvplCnsltList = cvplCnsltService.excelDownCvplCnsltMyList(searchVO);
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("cvplCnslt", cvplCnsltList);

        return new ModelAndView("cvplCnsltMyExcelView", "cvplCnsltMap", map);
    } 
    
    /**
	 * BEST 민원으로 셋팅한다.
	 * @param vo - 셋팅할 정보가 담긴 CvplCnsltVO vo
	 * @return /cvpl/egovCvplCnsltList.do 
	 * @exception Exception
	 */
    @RequestMapping("/cvpl/updateCvplCnsltBest.do")
    public String updateCvplCnsltBest(
            CvplCnsltVO cvplCnsltVO,
            @ModelAttribute("searchVO") CvplSearchVO searchVO, SessionStatus status)
            throws Exception {
    	if(egovWebServiceClientRegisterCvpl.registerCvpl(cvplCnsltVO)) {
            cvplCnsltService.updateCvplCnsltBest(cvplCnsltVO);
            status.setComplete();
    	}
        return "forward:/cvpl/egovCvplCnsltList.do";
    }

    
}
