package egovframework.rte.cvpl.web;

import java.io.File;

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

import javax.annotation.Resource;

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.service.CvplFaqVO;
import egovframework.rte.cvpl.service.CvplSearchVO;
import egovframework.rte.cvpl.service.EgovCvplFaqService;
import egovframework.rte.cvpl.util.EgovWebServiceClientRegisterCvpl;
import egovframework.rte.cvpl.util.EgovWebServiceClientRegisterFaq;
import egovframework.rte.fdl.property.EgovPropertyService;
import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;
import net.sourceforge.ajaxtags.xml.AjaxXmlBuilder;
import egovframework.rte.cvpl.web.view.CvplAjaxXmlView;

import egovframework.rte.cvpl.common.EgovCvplSessionAuth;
import egovframework.rte.fdl.security.userdetails.util.EgovUserDetailsHelper; 


/**
 * @Class Name : EgovCvplFaqController.java
 * @Description : EgovCvplFaq 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=CvplFaqVO.class)
public class EgovCvplFaqController {
	
	protected Log log = LogFactory.getLog(this.getClass());

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

	/** EgovWebServiceClientRegisterFaq */
    @Resource(name = "egovWebServiceClientRegisterFaq")
    private EgovWebServiceClientRegisterFaq egovWebServiceClientRegisterFaq;
    
	/**
	 * 글 목록을 조회한다. (pageing)
	 * @param searchVO - 조회할 정보가 담긴 CvplSearchVO
	 * @return "/cvpl/egovCvplFaqList"
	 * @exception Exception
	 */                 
    @RequestMapping(value="/cvpl/egovCvplFaqList.do")
    public String selectCvplFaqList(@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());
		
		searchVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
		searchVO.setLastIndex(paginationInfo.getLastRecordIndex());
		searchVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
		
        List cvplFaqList = cvplFaqService.selectCvplFaqList(searchVO);
        model.addAttribute("resultList", cvplFaqList);
        
        int totCnt = cvplFaqService.selectCvplFaqListTotCnt(searchVO);
		paginationInfo.setTotalRecordCount(totCnt);
        model.addAttribute("paginationInfo", paginationInfo);
        
        /** 공백이 아닌 경우, 검색어의 중복을 체크한다. */
        String searchKeyword = searchVO.getSearchKeyword();
        if (!searchKeyword.equals("")) {
	        String dupSrchKeyword = cvplFaqService.checkDupSearchKeywordList(searchKeyword);
	        
	        if (!searchKeyword.equals(dupSrchKeyword)) {
	            /** 검색어를 등록한다. */
	        	cvplFaqService.insertSearchKeywordList(searchKeyword);
	        }
        }
        
    	/* Session */
    	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	
        model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

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

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

    	/** user Name process*/
    	CvplFaqVO cvplFaqVO = new CvplFaqVO();
        cvplFaqVO.setUserName(egovCvplSessionAuth.getUserName());
    	
        model.addAttribute("cvplFaqVO", cvplFaqVO);
        model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

        return "/cvpl/EgovCvplFaqRegister";
    }
    
	/**
	 * FAQ를 등록한다.
	 * @param cvplFaqVO - 등록할 정보가 담긴 CvplFaqVO
	 * @return "/cvpl/egovCvplFaqList"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/addCvplFaq.do")
    public String addCvplFaq(
    		final MultipartHttpServletRequest multiRequest,
            @ModelAttribute("searchVO") CvplSearchVO searchVO, 
            CvplFaqVO cvplFaqVO,
            BindingResult bindingResult, Model model, SessionStatus status)
            throws Exception {
    	
    	/* Session */
    	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	

    	/** userId process*/
    	cvplFaqVO.setUserId(egovCvplSessionAuth.getUserId());
    	
    	/** admnstmachCode process*/
    	cvplFaqVO.setAdmnstmachCode(propertiesService.getString("myAdmnstmachValue"));
    	
    	/** From validate process*/
    	beanValidator.validate(cvplFaqVO, bindingResult);
    	
    	if (bindingResult.hasErrors()) {
    		model.addAttribute("cvplFaqVO", cvplFaqVO);
            model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

			return "/cvpl/EgovCvplFaqRegister";
    	}

    	/** 파일 처리 */
    	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("cvplFaqVO", cvplFaqVO);
            model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

			return "/cvpl/EgovCvplFaqRegister";
		}
		
		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())) {
				cvplFaqVO.setFaqAtch1(file.getOriginalFilename());
			}
			if(fileKey == 1 && !"".equals(file.getOriginalFilename())) {
				cvplFaqVO.setFaqAtch2(file.getOriginalFilename());
			}
			fileKey++;
		}
        
        cvplFaqService.insertCvplFaq(cvplFaqVO);
        status.setComplete();
        return "forward:/cvpl/egovCvplFaqList.do";
    }
    
	/**
	 * FAQ수정화면을 조회한다.
	 * @param searchVO - 조회할 정보가 담긴 CvplSearchVO
	 * @return "/cvpl/EgovCvplFaqUpdate"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/updateCvplFaqView.do")
    public String updateCvplFaqView(
            @RequestParam("selectedId") String id ,
            @ModelAttribute("searchVO") CvplSearchVO searchVO, Model model)
            throws Exception {
        CvplFaqVO cvplFaqVO = new CvplFaqVO();
        cvplFaqVO.setFaqNo(id);
        model.addAttribute(selectCvplFaq(cvplFaqVO, searchVO));
    	/* Session */
    	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	
        model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

        return "/cvpl/EgovCvplFaqUpdate";
    }

	/**
	 * FAQ 한건을 조회한다.
	 * @param searchVO - 조회할 정보가 담긴 CvplSearchVO
	 * @return "CvplFaqVO cvplFaqVO"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/selectCvplFaq.do")
    public @ModelAttribute("cvplFaqVO")
    CvplFaqVO selectCvplFaq(
            CvplFaqVO cvplFaqVO,
            @ModelAttribute("searchVO") CvplSearchVO searchVO) throws Exception {
        return cvplFaqService.selectCvplFaq(cvplFaqVO);
    }

	/**
	 * FAQ를 수정한다.
	 * @param cvplFaqVO - 수정할 정보가 담긴 CvplFaqVO
	 * @return "/cvpl/egovCvplFaqList"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/updateCvplFaq.do")
    public String updateCvplFaq(
    		final MultipartHttpServletRequest multiRequest,
    		@RequestParam("fileYN") String fileYN,
            @ModelAttribute("searchVO") CvplSearchVO searchVO, 
            CvplFaqVO cvplFaqVO,
            BindingResult bindingResult, Model model, SessionStatus status)
            throws Exception {

    	/** From validate process*/
    	beanValidator.validate(cvplFaqVO, bindingResult);
    	
    	if (bindingResult.hasErrors()) {
    		model.addAttribute("cvplFaqVO", cvplFaqVO);
        	/* Session */
        	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	
            model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

			return "/cvpl/EgovCvplFaqUpdate";
    	}

    	/** 파일을 새로 첨부했다면 */
    	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("cvplFaqVO", cvplFaqVO);
	        	/* Session */
	        	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	
	            model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

				return "/cvpl/EgovCvplFaqUpdate";
			}
			
			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())) {
					cvplFaqVO.setFaqAtch1(file.getOriginalFilename());
				}
				if(fileKey == 1 && !"".equals(file.getOriginalFilename())) {
					cvplFaqVO.setFaqAtch2(file.getOriginalFilename());
				}
				fileKey++;
			}
    	}
    	
        cvplFaqService.updateCvplFaq(cvplFaqVO);
        status.setComplete();
        return "forward:/cvpl/egovCvplFaqList.do";
    }
    
	/**
	 * FAQ를 삭제한다.
	 * @param cvplFaqVO - 삭제할 정보가 담긴 CvplFaqVO
	 * @return "/cvpl/egovCvplFaqList"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/deleteCvplFaq.do")
    public String deleteCvplFaq(
            CvplFaqVO cvplFaqVO,
            @ModelAttribute("searchVO") CvplSearchVO searchVO, SessionStatus status)
            throws Exception {
        cvplFaqService.deleteCvplFaq(cvplFaqVO);
        status.setComplete();
        return "forward:/cvpl/egovCvplFaqList.do";
    }

    @RequestMapping("/cvpl/viewCvplFaqView.do")
    public String viewCvplFaqView(
            @RequestParam("selectedId") String id ,
            @ModelAttribute("searchVO") CvplSearchVO searchVO, Model model)
            throws Exception {
        CvplFaqVO cvplFaqVO = new CvplFaqVO();
        cvplFaqVO.setFaqNo(id);
        model.addAttribute(selectCvplFaq(cvplFaqVO, searchVO));
    	/* Session */
    	EgovCvplSessionAuth egovCvplSessionAuth = (EgovCvplSessionAuth)EgovUserDetailsHelper.getAuthenticatedUser();    	
        model.addAttribute("egovCvplSessionAuth", egovCvplSessionAuth);

        return "/cvpl/EgovCvplFaqView";
    }

    /**
	 * 검색어의 자동완성기능을 구현한다.
	 * @param searchKeyword - 자동완성기능을 사용할 문자
	 * @return "/cvpl/egovCvplFaqList"
	 * @exception Exception
	 */                 
    @RequestMapping("/cvpl/egovCvplFaqSearchAjax.do")
	protected ModelAndView handle(@RequestParam("searchKeyword") String searchKeyword) 
    			throws Exception {
				
		ModelAndView model = new ModelAndView(new CvplAjaxXmlView());
		List<String> searchKeywordList = cvplFaqService.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 "cvplFaqExcelView"
	 * @exception Exception
	 */                 
    @RequestMapping(value="/cvpl/excelDownCvplFaqList.do")
    public ModelAndView excelDownCvplFaqList(@ModelAttribute("searchVO") CvplSearchVO searchVO)
            throws Exception {
    	
        List cvplFaqList = cvplFaqService.excelDownCvplFaqList(searchVO);
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("cvplFaq", cvplFaqList);

        return new ModelAndView("cvplFaqExcelView", "cvplFaqMap", map);
    } 
    
    /**
	 * BEST FAQ로 셋팅한다.
	 * @param vo - 셋팅할 정보가 담긴 CvplFaqVO vo
	 * @return /cvpl/egovCvplFaqList.do 
	 * @exception Exception
	 */
    @RequestMapping("/cvpl/updateCvplFaqBest.do")
    public String updateCvplFaqBest(
            CvplFaqVO cvplFaqVO,
            @ModelAttribute("searchVO") CvplSearchVO searchVO, SessionStatus status)
            throws Exception {
    	if(egovWebServiceClientRegisterFaq.registerFaq(cvplFaqVO)) {
            cvplFaqService.updateCvplFaqBest(cvplFaqVO);
            status.setComplete();
    	}
        return "forward:/cvpl/egovCvplFaqList.do";
    }

}
