package itn.let.cop.bbs.web;

import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

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

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springmodules.validation.commons.DefaultBeanValidator;

import egovframework.rte.fdl.property.EgovPropertyService;
import egovframework.rte.fdl.security.userdetails.util.EgovUserDetailsHelper;
import egovframework.rte.psl.dataaccess.util.EgovMap;
import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;
import itn.com.cmm.ComDefaultCodeVO;
import itn.com.cmm.ComDefaultVO;
import itn.com.cmm.EgovMessageSource;
import itn.com.cmm.LoginVO;
import itn.com.cmm.service.EgovCmmUseService;
import itn.let.cop.bbs.service.BoardMaster;
import itn.let.cop.bbs.service.BoardMasterVO;
import itn.let.cop.bbs.service.BoardVO;
import itn.let.cop.bbs.service.EgovBBSAttributeManageService;
import itn.let.cop.bbs.service.EgovBBSManageService;
import itn.let.cop.cmt.service.CommentVO;
import itn.let.cop.cmt.service.EgovArticleCommentService;
import itn.let.sec.ram.service.AuthorManageVO;
import itn.let.sec.ram.service.EgovAuthorManageService;
import itn.let.sym.site.service.EgovSiteManagerService;
import itn.let.uss.umt.service.EgovUserManageService;
import itn.let.uss.umt.service.UserDefaultVO;

/**
 * 게시판 속성관리를 위한 컨트롤러  클래스
 * @author 공통 서비스 개발팀 이삼섭
 * @since 2009.03.12
 * @version 1.0
 * @see
 *
 * <pre>
 * << 개정이력(Modification Information) >>
 *
 *   수정일      수정자          수정내용
 *  -------    --------    ---------------------------
 *  2009.03.12  이삼섭          최초 생성
 *  2009.06.26	한성곤		2단계 기능 추가 (댓글관리, 만족도조사)
 *  2011.08.31  JJY            경량환경 템플릿 커스터마이징버전 생성
 *
 *  </pre>
 */
@Controller
public class EgovBBSAttributeManageController {

	@Resource(name = "EgovBBSAttributeManageService")
	private EgovBBSAttributeManageService bbsAttrbService;

	@Resource(name = "EgovCmmUseService")
	private EgovCmmUseService cmmUseService;

	@Resource(name = "propertiesService")
	protected EgovPropertyService propertyService;

	@Autowired
	private DefaultBeanValidator beanValidator;

	@Resource(name = "egovAuthorManageService")
	private EgovAuthorManageService egovAuthorManageService;
	
	@Resource(name = "userManageService")
	private EgovUserManageService userManageService;

    @Resource(name="egovMessageSource")
    EgovMessageSource egovMessageSource;

	/** EgovPropertyService */
	@Resource(name = "propertiesService")
	protected EgovPropertyService propertiesService;

	@Resource(name = "egovSiteManagerService")
	EgovSiteManagerService egovSiteManagerService;
	
	@Resource(name = "EgovBBSManageService")
    private EgovBBSManageService bbsMngService;
	
	/** 댓글 */
	@Resource(name = "EgovArticleCommentService")
    protected EgovArticleCommentService egovArticleCommentService;
	
	//배열 정의{"컬럼순차번호, 컬럼이름, 컬럼내용, 컬럼이름에 붙여야할 내용(엑셀코드양식다운로드시 필요)"}
	private String[][] bbsMasterExcelValue ={
	    {"0" ,"번호" , "1" , "" },
	    {"1", "사이트명" , "ITN" , "[코드]"}, 
	    {"2", "게시판명" , "testId", ""}, 
	    {"3", "새글/총글수" , "홍길동", ""}, 
	    {"4", "게시판유형" , "일반관리자", "[코드]"},
	    {"5", "사용여부" , "test@itn.co.kr", ""},
	    {"6", "생성일" , "02-123-4567", ""} 
	} ;
	
	
	/**
	 * 게시글 목록을 조회한다.
	 *
	 * @param boardMasterVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/cop/bbs/SelectBbsContentsList.do")
	public String SelectBbsContentsList(@ModelAttribute("searchVO") BoardVO boardVO, 
			ModelMap model , HttpSession session) throws Exception {
		List<String> authorities = EgovUserDetailsHelper.getAuthorities();
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		
		// 게시판 설정 관리권한 체크
		boolean bbsAttrMngAuth = false;
		for (String authority : authorities) {
			if (authority.equals("ROLE_ADMIN")) bbsAttrMngAuth = true;
		}
		
		if(boardVO.getPageUnit() != 10) {
			boardVO.setPageUnit(boardVO.getPageUnit());
		}
		
		PaginationInfo paginationInfo = new PaginationInfo();

		paginationInfo.setCurrentPageNo(boardVO.getPageIndex());
		paginationInfo.setRecordCountPerPage(boardVO.getPageUnit());
		paginationInfo.setPageSize(boardVO.getPageSize());

		boardVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
		boardVO.setLastIndex(paginationInfo.getLastRecordIndex());
		boardVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
		
		if("".equals(boardVO.getSearchSortCnd())){ //최초조회시 최신것 조회List
			boardVO.setSearchSortCnd("frstRegisterPnttm");
			boardVO.setSearchSortOrd("desc");
		}

		List<BoardVO> adminBoardList = bbsMngService.selectAdminMainBoard(boardVO);
		int totCnt = 0;
		 if(adminBoardList.size() > 0) {
			totCnt = adminBoardList.get(0).getTotcnt();
		}
		 
		paginationInfo.setTotalRecordCount(totCnt);
		model.addAttribute("adminBoardList", adminBoardList);
		model.addAttribute("paginationInfo", paginationInfo);
		model.addAttribute("searchVO", boardVO);
		
		model.addAttribute("pageUnit", boardVO.getPageUnit());
		model.addAttribute("searchCnd", boardVO.getSearchCnd());
		model.addAttribute("searchWrd", boardVO.getSearchWrd());
		
		//답변 조회
		CommentVO commentVO = new CommentVO();
		commentVO.setBbsId(boardVO.getBbsId());
		List<?> commentList = egovArticleCommentService.selectArticleCommentListAllList(commentVO);
		
		int commentCnt = commentList.size();
		model.addAttribute("commentCnt", commentCnt);
		model.addAttribute("commentList", commentList);		
		
		return "cop/bbs/EgovBoardContentsList";
	}
	
	
	/**
	 * 게시판 마스터 목록을 조회한다.
	 *
	 * @param boardMasterVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/cop/bbs/SelectBBSMasterInfs.do")
	public String selectBBSMasterInfs(@ModelAttribute("searchVO") BoardMasterVO boardMasterVO, 
			ModelMap model , HttpSession session) throws Exception {
		List<String> authorities = EgovUserDetailsHelper.getAuthorities();
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		
		// 게시판 설정 관리권한 체크
		boolean bbsAttrMngAuth = false;
		for (String authority : authorities) {
			if (authority.equals("ROLE_ADMIN")) bbsAttrMngAuth = true;
		}
		
		if (!bbsAttrMngAuth) boardMasterVO.setBbsMngId(user.getId());
		
		if(boardMasterVO.getPageUnit() != 10) {
			boardMasterVO.setPageUnit(boardMasterVO.getPageUnit());
		}
		
		PaginationInfo paginationInfo = new PaginationInfo();

		paginationInfo.setCurrentPageNo(boardMasterVO.getPageIndex());
		paginationInfo.setRecordCountPerPage(boardMasterVO.getPageUnit());
		paginationInfo.setPageSize(boardMasterVO.getPageSize());

		boardMasterVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
		boardMasterVO.setLastIndex(paginationInfo.getLastRecordIndex());
		boardMasterVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());

		if(null != user && !"super".equals(user.getSiteId())){
			boardMasterVO.setSiteId(user.getSiteId()) ; //사이트 아이디
		}
		
		if("".equals(boardMasterVO.getSearchSortCnd())){ //최초조회시 최신것 조회List
			boardMasterVO.setSearchSortCnd("BBS_ID");
			boardMasterVO.setSearchSortOrd("desc");
			boardMasterVO.setUseAt("Y"); //사용하는 것만 조회
		}else {
			if("".equals(boardMasterVO.getUseAt())){ //사용
				boardMasterVO.setUseAt("Y"); 	
			}
		}
		
		Map<String, Object> map = bbsAttrbService.selectBBSMasterInfs(boardMasterVO);

		int totCnt = Integer.parseInt((String) map.get("resultCnt"));
		//게시판 관리자 정보 가져오기
		List<BoardMasterVO> adminBbsList = (List<BoardMasterVO>)map.get("resultList");
		
		//사용자 bbs url가져오기
		String bbsHomeUrl = "/web/cop/bbsWeb/selectBoardList.do?bbsId="; //초기값
		for (BoardMasterVO tempVO: adminBbsList){
			List<EgovMap> mngIdList = new  ArrayList<>();
			mngIdList = bbsAttrbService.selectBBSMngIdList(tempVO);
			tempVO.setMngIdList(mngIdList);
			tempVO.setBbsHomeUrl(getBbsUrl(tempVO.getBbsId(), bbsHomeUrl));
		}
		paginationInfo.setTotalRecordCount(totCnt);

		model.addAttribute("resultList", map.get("resultList"));
		model.addAttribute("resultCnt", map.get("resultCnt"));
		model.addAttribute("bbsAttrMngAuth", bbsAttrMngAuth);
		model.addAttribute("paginationInfo", paginationInfo);
		return "cop/bbs/EgovBoardMstrList";
	}

	/**
	 * 게시판 마스터 정보를 삭제한다.
	 *
	 * @param boardMasterVO
	 * @param boardMaster
	 * @param status
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/cop/bbs/DeleteBBSMasterInf.do")
	public String deleteBBSMasterInf(@ModelAttribute("searchVO") BoardMasterVO boardMasterVO, @ModelAttribute("boardMaster") BoardMaster boardMaster, SessionStatus status
			, RedirectAttributes redirectAttributes) throws Exception {
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		
		// 게시판 설정 관리권한 체크
		boolean bbsAttrMngAuth = false;
		List<String> authorities = EgovUserDetailsHelper.getAuthorities();
		for (String authority : authorities) {
			if (authority.equals("ROLE_ADMIN")) bbsAttrMngAuth = true;
		}
		if (!bbsAttrMngAuth) {
			redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("fail.common.auth"));
			return "redirect:/cop/bbs/SelectBBSMasterInfs.do";
		}

		boardMaster.setLastUpdusrId(user.getUniqId());
		bbsAttrbService.deleteBBSMasterInf(boardMaster);
		
		redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("success.common.delete"));
		return "redirect:/cop/bbs/SelectBBSMasterInfs.do";
	}

	/**
	 * 신규 게시판 마스터 등록을 위한 등록페이지로 이동한다.
	 *
	 * @param boardMasterVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/cop/bbs/addBBSMaster.do")
	public String addBBSMaster(@ModelAttribute("searchVO") BoardMasterVO boardMasterVO, @ModelAttribute("boardMaster") BoardMaster boardMaster,
			ModelMap model, BindingResult bindingResult, RedirectAttributes redirectAttributes,
			HttpSession session ) throws Exception {
		// 게시판 설정 관리권한 체크
		boolean bbsAttrMngAuth = false;
		List<String> authorities = EgovUserDetailsHelper.getAuthorities();
		for (String authority : authorities) {
			if (authority.equals("ROLE_ADMIN")) bbsAttrMngAuth = true;
		}
		if (!bbsAttrMngAuth) {
			redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("fail.common.auth"));
			return "redirect:/cop/bbs/SelectBBSMasterInfs.do";
		}

		// 게시판 공통코드 및 권한목록 Set
		setBBSModelInfo(model);
		return "cop/bbs/EgovBoardMstrRegist";
	}
	
	/**
	 * 신규 게시판 마스터 정보를 등록한다.
	 *
	 * @param boardMasterVO
	 * @param boardMaster
	 * @param status
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/cop/bbs/insertBBSMasterInf.do")
	public String insertBBSMasterInf(@ModelAttribute("searchVO") BoardMasterVO boardMasterVO, @ModelAttribute("boardMaster") BoardMaster boardMaster, BindingResult bindingResult,
			SessionStatus status, ModelMap model, RedirectAttributes redirectAttributes, HttpSession session) throws Exception {
		// 게시판 설정 관리권한 체크
		boolean bbsAttrMngAuth = false;
		List<String> authorities = EgovUserDetailsHelper.getAuthorities();
		for (String authority : authorities) {
			if (authority.equals("ROLE_ADMIN")) bbsAttrMngAuth = true;
		}
		if (!bbsAttrMngAuth) {
			redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("fail.common.auth"));
			return "redirect:/cop/bbs/SelectBBSMasterInfs.do";
		}
		
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		beanValidator.validate(boardMaster, bindingResult);
		if (bindingResult.hasErrors()) {
			model.addAttribute("siteId", user.getSiteId());
			// 게시판 공통코드 및 권한목록 Set
			setBBSModelInfo(model);
			return "cop/bbs/EgovBoardMstrRegist";
		}


		boardMaster.setFrstRegisterId(user.getUniqId());
		// eGov 게시판 유형 코드. BBSA03:기본게시판. (게시판 타입코드로 기본,웹진,포토 사용중. 유형 코드 필요 유무 확인필요)
		boardMaster.setBbsAttrbCode("BBSA03"); 
		if(null != user && !"super".equals(user.getSiteId())){  //리스트, 수정, 입력
			boardMaster.setSiteId(user.getSiteId());//사이트 아이디
		}
		
		bbsAttrbService.insertBBSMastetInf(boardMaster);
		redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("success.common.insert"));
		return "redirect:/cop/bbs/SelectBBSMasterInfs.do";
	}
	
	/**
	 * 게시판 마스터 상세내용을 조회한다.
	 *
	 * @param boardMasterVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/cop/bbs/SelectBBSMasterInf.do")
	public String selectBBSMasterInf(@ModelAttribute("searchVO") BoardMasterVO searchVO, ModelMap model, 
			RedirectAttributes redirectAttributes, HttpSession session) throws Exception {
		// 게시판 설정 관리권한 체크
		boolean bbsAttrMngAuth = false;
		List<String> authorities = EgovUserDetailsHelper.getAuthorities();
		for (String authority : authorities) {
			if (authority.equals("ROLE_ADMIN") || authority.equals("ROLE_USER_MEMBER")) bbsAttrMngAuth = true;
		}
		if (!bbsAttrMngAuth) {
			redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("fail.common.auth"));
			return "redirect:/cop/bbs/SelectBBSMasterInfs.do";
		}
		
		BoardMasterVO vo = bbsAttrbService.selectBBSMasterInf(searchVO);
		model.addAttribute("boardMaster", vo);
		
		// 게시판 관리자ID 조회
		List<EgovMap> mngIdList = bbsAttrbService.selectBBSMngIdList(searchVO);
		model.addAttribute("mngIdList", mngIdList);
		
		// 게시판 공통코드 및 권한목록 Set
		setBBSModelInfo(model);
		
		BoardMaster siteMainNbsVO = new BoardMaster();
		siteMainNbsVO = bbsAttrbService.getSiteMainNbsVO(searchVO);
		model.addAttribute("siteMainNbsVO", siteMainNbsVO);
		
		if(EgovUserDetailsHelper.getAuthorities().contains("ROLE_ADMIN")){
			model.addAttribute("ROLE_ADMIN", "ROLE_ADMIN");
		}
		return "cop/bbs/EgovBoardMstrUpdt";
	}
	
	/**
	 * 게시판 마스터 정보를 수정한다.
	 *
	 * @param boardMasterVO
	 * @param boardMaster
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/cop/bbs/UpdateBBSMasterInf.do")
	public String updateBBSMasterInf(@ModelAttribute("searchVO") BoardMasterVO boardMasterVO, @ModelAttribute("boardMaster") BoardMaster boardMaster, BindingResult bindingResult,
			ModelMap model, RedirectAttributes redirectAttributes) throws Exception {
		
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		// 게시판 설정 관리권한 체크
		boolean bbsAttrMngAuth = false;
		List<String> authorities = EgovUserDetailsHelper.getAuthorities();
		for (String authority : authorities) {
			if (authority.equals("ROLE_ADMIN")) bbsAttrMngAuth = true;
		}
		if (!bbsAttrMngAuth) {
			redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("fail.common.auth"));
			return "redirect:/cop/bbs/SelectBBSMasterInfs.do";
		}

		beanValidator.validate(boardMaster, bindingResult);
		if (bindingResult.hasErrors()) {
			model.addAttribute("siteId", user.getSiteId());
			// 게시판 공통코드 및 권한목록 Set
			setBBSModelInfo(model);
			return "cop/bbs/EgovBoardMstrUpdt";
		}

		if(null != user && !"super".equals(user.getSiteId())){
			boardMaster.setSiteId(user.getSiteId());
		}
		
		boardMaster.setLastUpdusrId(user.getUniqId());
		bbsAttrbService.updateBBSMasterInf(boardMaster);  //BBST07 사전정보공표
		
		//매인 bbs 등록 
		LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		if(null != loginVO && !"super".equals(loginVO.getSiteId())){  //리스트, 수정, 입력
			boardMaster.setSiteId(loginVO.getSiteId());
			boardMasterVO.setSiteId(loginVO.getSiteId());
		}
		
		//변경이 되면 업데이트 함.
		BoardMaster siteMainNbsVO = new BoardMaster();
		siteMainNbsVO = bbsAttrbService.getSiteMainNbsVO(boardMasterVO);
		
		if(boardMaster.getNoticeBbsid().equals("") && siteMainNbsVO !=null){//체크안했을 경우 이전 값이 있을때 변경
			if(boardMasterVO.getBbsId().equals(siteMainNbsVO.getNoticeBbsid())){
				bbsAttrbService.insupNoticeBbsid(boardMaster) ;
			}
		}else{
			bbsAttrbService.insupNoticeBbsid(boardMaster) ;
		}
		
		if(boardMaster.getQnaBbsid().equals("")){//체크안했을 경우 이전 값이 있을때 변경
			if(siteMainNbsVO !=null && boardMasterVO.getBbsId().equals(siteMainNbsVO.getQnaBbsid())){
				bbsAttrbService.insupQnaBbsid(boardMaster) ;
			}
		}else{
			bbsAttrbService.insupQnaBbsid(boardMaster) ;
		}

		if(boardMaster.getNewsBbsid().equals("")){//체크안했을 경우 이전 값이 있을때 변경
			if(siteMainNbsVO !=null && boardMasterVO.getBbsId().equals(siteMainNbsVO.getNewsBbsid())){
				bbsAttrbService.insupNewsBbsid(boardMaster) ;
			}
		}else{
			bbsAttrbService.insupNewsBbsid(boardMaster) ;
		}
		
		if(boardMaster.getLibraryBbsid().equals("")){//체크안했을 경우 이전 값이 있을때 변경
			if(siteMainNbsVO !=null && boardMasterVO.getBbsId().equals(siteMainNbsVO.getLibraryBbsid())){
				bbsAttrbService.insupLibraryBbsid(boardMaster) ;
			}
		}else{
			bbsAttrbService.insupLibraryBbsid(boardMaster) ;
		}
		
		redirectAttributes.addAttribute("pageIndex", boardMasterVO.getPageIndex());
		redirectAttributes.addAttribute("searchCnd", boardMasterVO.getSearchCnd());
		redirectAttributes.addAttribute("searchWrd", boardMasterVO.getSearchWrd());
		redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("success.common.update"));
		return "redirect:/cop/bbs/SelectBBSMasterInfs.do";
	}
	
	/**
	 * 팝업을 위한 게시판 관리자 목록을 조회한다.
	 *
	 * @param boardMasterVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/cop/bbs/selectBBSMngInfsPop.do")
	public String selectBBSmngInfsPop(@ModelAttribute("userSearchVO") UserDefaultVO userSearchVO, @RequestParam Map<String, Object> commandMap, ModelMap model) throws Exception {
		/** EgovPropertyService */
		userSearchVO.setPageUnit(propertyService.getInt("pageUnit"));
		userSearchVO.setPageSize(propertyService.getInt("pageSize"));

		/** pageing */
		PaginationInfo paginationInfo = new PaginationInfo();
		paginationInfo.setCurrentPageNo(userSearchVO.getPageIndex());
		paginationInfo.setRecordCountPerPage(userSearchVO.getPageUnit());
		paginationInfo.setPageSize(userSearchVO.getPageSize());

		userSearchVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
		userSearchVO.setLastIndex(paginationInfo.getLastRecordIndex());
		userSearchVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());

		model.addAttribute("resultList", userManageService.selectUserList(userSearchVO));
		int totCnt = userManageService.selectUserListTotCnt(userSearchVO);
		model.addAttribute("resultCnt", totCnt);
		
		paginationInfo.setTotalRecordCount(totCnt);
		model.addAttribute("paginationInfo", paginationInfo);

		return "cop/bbs/EgovBoardMngInfsPop";
	}

    /**
	 * 게시판 관리자 추가 등록
	 * @param commandMap 파라메터전달용 commandMap
	 * @param model 화면모델
	 * @throws Exception
	 */
	@RequestMapping(value = "/cop/bbs/insertBBSMngInfAjax.do")
	public ModelAndView insertBBSMngInfAjax(@RequestParam Map<String, Object> commandMap) throws Exception {
		
    	ModelAndView modelAndView = new ModelAndView();
    	modelAndView.setViewName("jsonView");

		String bbsMngId = (String) commandMap.get("bbsMngId");
		String bbsId = (String) commandMap.get("bbsId");
		BoardMaster vo = new BoardMaster();
		vo.setBbsId(bbsId);
		vo.setBbsMngId(bbsMngId);
		
		int mngId = bbsAttrbService.insertBBSMngInf(vo);
		modelAndView.addObject("bbsMngId", bbsMngId);
		modelAndView.addObject("mngId", mngId);

		return modelAndView;
	}
	
	/**
	 * 게시판 관리자 삭제
	 * @param commandMap 파라메터전달용 commandMap
	 * @throws Exception
	 */
	@RequestMapping(value = "/cop/bbs/deleteBBSMngInfAjax.do")
	public ModelAndView deleteBBSMngInfAjax(@RequestParam Map<String, Object> commandMap) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("jsonView");
		
		String mngId = (String) commandMap.get("mngId");
		
		BoardMaster vo = new BoardMaster();
		vo.setMngId(Integer.parseInt(mngId));
		
		bbsAttrbService.deleteBBSMngInf(vo);
		
		modelAndView.addObject("mngId", mngId);
		return modelAndView;
	}
	
	/**
	 * 게시판 관리 권한 여부 체크
	 * @param manageAuth 게시판 관리권한
	 * @param mngIdList 게시판 관리자 목록 (없을 시 null)
	 * @param bbsId 게시판Id (게시판 관리자ID 목록 없을 시 조회하기 위한 게시판ID. 게시판 관리자 목록 있을 시 null) 
	 * @return boolean
	 * @throws Exception 
	 */
	private boolean isBBSManageAuthFlag(String manageAuth, List<EgovMap> mngIdList, String bbsId) throws Exception {
		boolean authFlag = false;
		List<String> authorities = EgovUserDetailsHelper.getAuthorities();
		LoginVO user = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
		
		if (manageAuth == null) {
			BoardMasterVO vo = new BoardMasterVO();
			vo.setBbsId(bbsId);
			vo = bbsAttrbService.selectBBSMasterInf(vo);
			manageAuth = vo.getManageAuth();
		}
		
		// 게시판 관리권한 체크
		for (String authority : authorities) {
			if (authority.equals(manageAuth)) authFlag = true;
		}
		
		// 게시판 관리자 체크
		if (!authFlag) {
			if (mngIdList == null) {
				BoardMaster vo = new BoardMaster();
				vo.setBbsId(bbsId);
				mngIdList = (List<EgovMap>)bbsAttrbService.selectBBSMngIdList(vo);
			}
			
			int mngYn = 0;
			for(int i = 0; i < mngIdList.size(); i++) {
				String emplyrId = (String) mngIdList.get(i).get("emplyrId");
				if (emplyrId.equals(user.getId())) mngYn++;
			}
			
			if (mngYn != 0) authFlag = true;
		}
		
		return authFlag;
	}

	/**
	 * 게시판 공통코드 및 권한목록 Set
	 * @param model
	 * @throws Exception 
	 */
	private void setBBSModelInfo(ModelMap model) throws Exception {
		ComDefaultCodeVO comDefaultCodeVO = new ComDefaultCodeVO();
		comDefaultCodeVO.setCodeId("COM004");
		List<?> codeResult = cmmUseService.selectCmmCodeDetail(comDefaultCodeVO);
		model.addAttribute("typeList", codeResult);
		comDefaultCodeVO.setCodeId("COM009");
		codeResult = cmmUseService.selectCmmCodeDetail(comDefaultCodeVO);
		model.addAttribute("attrbList", codeResult);
		comDefaultCodeVO.setCodeId("COM005");
		codeResult = cmmUseService.selectCmmCodeDetail(comDefaultCodeVO);
		model.addAttribute("tmptList", codeResult);
		
		AuthorManageVO authorManageVO = new AuthorManageVO();
		authorManageVO.setAuthorManageList(egovAuthorManageService.selectAuthorAllList(authorManageVO));
	    model.addAttribute("authorList", authorManageVO.getAuthorManageList());
	}
	
	
	/**
	 * @@@@@@사용자 Test 용. 추후 삭제 @@@@@
	 * 게시판 마스터 목록을 조회한다.
	 *
	 * @param boardMasterVO
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/cop/bbs/SelectBBSMasterInfsUsr.do")
	public String selectBBSMasterInfsUsr(@ModelAttribute("searchVO") BoardMasterVO boardMasterVO, ModelMap model) throws Exception {
		
		boardMasterVO.setPageUnit(propertyService.getInt("pageUnit"));
		boardMasterVO.setPageSize(propertyService.getInt("pageSize"));

		PaginationInfo paginationInfo = new PaginationInfo();

		paginationInfo.setCurrentPageNo(boardMasterVO.getPageIndex());
		paginationInfo.setRecordCountPerPage(boardMasterVO.getPageUnit());
		paginationInfo.setPageSize(boardMasterVO.getPageSize());

		boardMasterVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
		boardMasterVO.setLastIndex(paginationInfo.getLastRecordIndex());
		boardMasterVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());

		Map<String, Object> map = bbsAttrbService.selectBBSMasterInfs(boardMasterVO);
		int totCnt = Integer.parseInt((String) map.get("resultCnt"));

		paginationInfo.setTotalRecordCount(totCnt);

		model.addAttribute("resultList", map.get("resultList"));
		model.addAttribute("resultCnt", map.get("resultCnt"));
		model.addAttribute("paginationInfo", paginationInfo);

		return "cop/bbs/EgovBoardMstrList";
	}

	/**
	 * 게시판 ID를 조회한다.
	 * @param searchVO ComDefaultVO
	 * @return 출력페이지정보 "cop/bbs/EgovBoardIdSearch"
	 * @exception Exception
	 */
	@RequestMapping(value = "/cop/bbs/EgovBBSIdListSearch.do")
	public String selectBBSIdListSearch(@ModelAttribute("searchVO") ComDefaultVO searchVO, ModelMap model) throws Exception {
		
		// 0. Spring Security 사용자권한 처리
		Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
		if (!isAuthenticated) {
			model.addAttribute("message", egovMessageSource.getMessage("fail.common.login"));
			return "uat/uia/EgovLoginUsr";
		}
		// 내역 조회
		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());

		Map<String, Object> map = bbsAttrbService.selectBBSIdList(searchVO);
		int totCnt = Integer.parseInt((String) map.get("resultCnt"));

		paginationInfo.setTotalRecordCount(totCnt);

		model.addAttribute("resultList", map.get("resultList"));
		model.addAttribute("paginationInfo", paginationInfo);
		
		return "cop/bbs/EgovBoardIdSearch";
	}

	/**
	 * 선택된 게시판을 삭제한다.
	 * @param bbsIds String
	 * @param boardMasterVO BoardMasterVO
	 * @return String
	 * @exception Exception
	 */
	@RequestMapping(value = "/cop/bbs/DeleteBBSMasterInfs.do")
	public String deleteBBSMasterInfs(@RequestParam("bbsIds") String bbsIds, @ModelAttribute("BoardMasterVO") BoardMasterVO boardMasterVO, RedirectAttributes redirectAttributes)
			throws Exception {

		// 게시판 설정 관리권한 체크
		boolean bbsAttrMngAuth = false;
		LoginVO loginVo = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser() ;
		if("ROLE_ADMIN".equals(loginVo.getAuthority())){
			 bbsAttrMngAuth = true;
		}
		
		if (!bbsAttrMngAuth) {
			redirectAttributes.addFlashAttribute("message", egovMessageSource.getMessage("fail.common.auth"));
			return "redirect:/cop/bbs/SelectBBSMasterInfs.do";
		}

		String[] strBbsIds = bbsIds.split(";");
		for (int i = 0; i < strBbsIds.length; i++) {
			boardMasterVO.setBbsId(strBbsIds[i]);
			bbsAttrbService.deleteBBSMasterInf(boardMasterVO);
		}
		
		// status.setComplete();	// ?
		
		boardMasterVO.setPageIndex(1);
		redirectAttributes.addAttribute("pageIndex", boardMasterVO.getPageIndex());
		redirectAttributes.addAttribute("searchCnd", boardMasterVO.getSearchCnd());
		redirectAttributes.addAttribute("searchWrd", boardMasterVO.getSearchWrd());
		redirectAttributes.addFlashAttribute("message", "정상적으로 처리 되었습니다.");
		return "redirect:/cop/bbs/SelectBBSMasterInfs.do";
	}
	
	public String getBbsUrl(String bbsId , String bbsHomeUrl){
		//원자력소식
		if("BBSMSTR_000000000411".equals(bbsId)
		  ||"BBSMSTR_000000000412".equals(bbsId)
     	){bbsHomeUrl = "/web/cop/bbs/NewsList.do"; return bbsHomeUrl ;} 
		//자료실
		if("BBSMSTR_000000000493".equals(bbsId)
		  ||"BBSMSTR_000000000477".equals(bbsId)
		  ||"BBSMSTR_000000000476".equals(bbsId)
		  ||"BBSMSTR_000000000475".equals(bbsId)
		  ||"BBSMSTR_000000000474".equals(bbsId)
		  ||"BBSMSTR_000000000473".equals(bbsId)
		  ||"BBSMSTR_000000000472".equals(bbsId)
		  ||"BBSMSTR_000000000471".equals(bbsId)
		  ||"BBSMSTR_000000000461".equals(bbsId)
     	){bbsHomeUrl = "/web/cop/bbs/LibList.do?bbsId="+bbsId; return bbsHomeUrl ;}
		
		//자주하는질문
		if("BBSMSTR_000000000429".equals(bbsId)
		  ||"BBSMSTR_000000000428".equals(bbsId)
		  ||"BBSMSTR_000000000427".equals(bbsId)
		  ||"BBSMSTR_000000000426".equals(bbsId)
		  ||"BBSMSTR_000000000425".equals(bbsId)
		  ||"BBSMSTR_000000000424".equals(bbsId)
		  ||"BBSMSTR_000000000423".equals(bbsId)
		  ||"BBSMSTR_000000000422".equals(bbsId)
		  ||"BBSMSTR_000000000421".equals(bbsId)
     	){bbsHomeUrl = "/web/cop/bbs/FaqList.do"; return bbsHomeUrl ;}
		
		//묻고답하기
		if("BBSMSTR_000000000528".equals(bbsId)
		  ||"BBSMSTR_000000000527".equals(bbsId)
		  ||"BBSMSTR_000000000526".equals(bbsId)
		  ||"BBSMSTR_000000000525".equals(bbsId)
		  ||"BBSMSTR_000000000524".equals(bbsId)
		  ||"BBSMSTR_000000000523".equals(bbsId)
		  ||"BBSMSTR_000000000522".equals(bbsId)
		  ||"BBSMSTR_000000000521".equals(bbsId)
		  ||"BBSMSTR_000000000490".equals(bbsId)
     	){bbsHomeUrl = "/web/cop/bbs/QnaList.do"; return bbsHomeUrl ;}
		
		//사전정보공표
		if("BBSMSTR_000000000541".equals(bbsId)
		  ||"BBSMSTR_000000000456".equals(bbsId)
		  ||"BBSMSTR_000000000455".equals(bbsId)
		  ||"BBSMSTR_000000000454".equals(bbsId)
		  ||"BBSMSTR_000000000453".equals(bbsId)
		  ||"BBSMSTR_000000000452".equals(bbsId)
		  ||"BBSMSTR_000000000451".equals(bbsId)
		  ||"BBSMSTR_000000000445".equals(bbsId)
		  ||"BBSMSTR_000000000444".equals(bbsId)
		  ||"BBSMSTR_000000000443".equals(bbsId)
		  ||"BBSMSTR_000000000442".equals(bbsId)
     	){bbsHomeUrl = "/web/cop/bbs/PubOperList.do?bbsId="+bbsId; return bbsHomeUrl ;}
		
		//통합경영공시
		if("BBSMSTR_000000000581".equals(bbsId)
		 ||"BBSMSTR_000000000582".equals(bbsId)		 
		 ||"BBSMSTR_000000000583".equals(bbsId)		 
		 ||"BBSMSTR_000000000584".equals(bbsId)		 
     	){bbsHomeUrl = "/web/content.do?proFn=9640000"; return bbsHomeUrl ;}
		
		//사전정보공표(하단 리스트 게시판 ) BBSMSTR_000000000442 ~  
		if("BBSMSTR_000000000599".equals(bbsId)
		  ||"BBSMSTR_000000000551".equals(bbsId)
		  ||"BBSMSTR_000000000598".equals(bbsId)
		  ||"BBSMSTR_000000000597".equals(bbsId)
		  ||"BBSMSTR_000000000596".equals(bbsId)
		  ||"BBSMSTR_000000000595".equals(bbsId)
		  ||"BBSMSTR_000000000594".equals(bbsId)
		  ||"BBSMSTR_000000000593".equals(bbsId)
		  ||"BBSMSTR_000000000571".equals(bbsId)
		  
		  ||"BBSMSTR_000000000602".equals(bbsId)
		  ||"BBSMSTR_000000000601".equals(bbsId)
		  ||"BBSMSTR_000000000600".equals(bbsId)
		  ||"BBSMSTR_000000000592".equals(bbsId)
		  ||"BBSMSTR_000000000591".equals(bbsId)
		  
		  ||"BBSMSTR_000000000608".equals(bbsId)
		  ||"BBSMSTR_000000000607".equals(bbsId)
		  ||"BBSMSTR_000000000606".equals(bbsId)
		  ||"BBSMSTR_000000000605".equals(bbsId)
		  ||"BBSMSTR_000000000604".equals(bbsId)
		  ||"BBSMSTR_000000000603".equals(bbsId)
		  
		  
		  ||"BBSMSTR_000000000614".equals(bbsId)
		  ||"BBSMSTR_000000000613".equals(bbsId)
		  ||"BBSMSTR_000000000612".equals(bbsId)
		  ||"BBSMSTR_000000000611".equals(bbsId)
		  ||"BBSMSTR_000000000610".equals(bbsId)
		  ||"BBSMSTR_000000000609".equals(bbsId)
		  
		  ||"BBSMSTR_000000000632".equals(bbsId)
		  ||"BBSMSTR_000000000631".equals(bbsId)
		  ||"BBSMSTR_000000000630".equals(bbsId)
		  
		  ||"BBSMSTR_000000000616".equals(bbsId)
		  ||"BBSMSTR_000000000615".equals(bbsId)
		  
		  ||"BBSMSTR_000000000618".equals(bbsId)
		  ||"BBSMSTR_000000000617".equals(bbsId)
		  
		  ||"BBSMSTR_000000000621".equals(bbsId)
		  ||"BBSMSTR_000000000620".equals(bbsId)
		  ||"BBSMSTR_000000000619".equals(bbsId)
		  
		  ||"BBSMSTR_000000000625".equals(bbsId)
		  ||"BBSMSTR_000000000622".equals(bbsId)
		  
		  ||"BBSMSTR_000000000629".equals(bbsId)
     	){bbsHomeUrl = "/web/cop/bbs/PubOperList.do?pubDetail=Y&bbsId="+bbsId; return bbsHomeUrl ;}
		return bbsHomeUrl+bbsId;
	}
	
	
	//게시판 마스터 리스트 엑셀 다운로드
  	@RequestMapping(value="/cop/bbs/bbsMasterExcelDownload.do")
  	public void bbsMasterExcelDownload( BoardMasterVO boardMasterVO, 
  			HttpServletRequest request, 
  			HttpServletResponse response , 
  			ModelMap model) throws Exception {
  		
  		boardMasterVO.setRecordCountPerPage(100000);
  		boardMasterVO.setFirstIndex(0);
  		LoginVO loginVO = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
		if(null != loginVO && !"super".equals(loginVO.getSiteId())){
			boardMasterVO.setSiteId(loginVO.getSiteId());
		}
  		// 메모리에 100개의 행을 유지합니다. 행의 수가 넘으면 디스크에 적습니다.
  		SXSSFWorkbook wb = new SXSSFWorkbook(100);
  		CellStyle style = wb.createCellStyle();
  		style.setBorderBottom(CellStyle.BORDER_THIN); //테두리 두껍게 
   		style.setBorderLeft(CellStyle.BORDER_THIN);
   		style.setBorderRight(CellStyle.BORDER_THIN);
   		style.setBorderTop(CellStyle.BORDER_THIN);
   		Font font = wb.createFont();
   		font.setBoldweight(Font.BOLDWEIGHT_BOLD);  //글씨 bold
   		
  		Cell cell = null;
  		Row row = null;
  		
  		String fileName ="게시판 마스터 리스트";
  		
  		String sheetTitle = ""; 
  		try{
  			//List<?> userSearchList  = userManageService.selectUserList(userSearchVO) ;
  			boardMasterVO.setDelSttus("Y");
  			Map<String, Object> bbsMasterList = bbsAttrbService.selectBBSMasterInfs(boardMasterVO);
  			{ //화면 리스트
  				sheetTitle = "게시판 마스터 리스트(화면)" ; //제목
  				Sheet sheet = wb.createSheet(sheetTitle);
  				row = sheet.createRow(0);
  		        for(int i=0 ; i < bbsMasterExcelValue.length ; i++) {
  	 		       cell = row.createCell(i);
  	 		       cell.setCellStyle(style);
  		 	       cell.setCellValue(bbsMasterExcelValue[i][1]);
  	 		    }
  			    
  		        List<BoardMasterVO> bbsMasterCastList =  (List<BoardMasterVO>)bbsMasterList.get("resultList") ;
  		        for(int i=0; i <  bbsMasterCastList.size(); i++){
  			    	row = sheet.createRow(i+1);
  			    	for(int j=0 ; j < bbsMasterExcelValue.length ; j++) {
  			        	cell = row.createCell(j);
  			        	cell.setCellStyle(style);
  			        	if(j==0) cell.setCellValue(i+1); //번호
  			        	if(j==1) cell.setCellValue(((BoardMasterVO)bbsMasterCastList.get(i)).getSiteNm()); //사이트명
  			        	if(j==2) cell.setCellValue(((BoardMasterVO)bbsMasterCastList.get(i)).getBbsNm()); //게시판명
  			        	if(j==3) cell.setCellValue(((BoardMasterVO)bbsMasterCastList.get(i)).getNewCnt()+"/"+ ((BoardMasterVO)bbsMasterCastList.get(i)).getTotCnt()); //새글/총글수
  			        	if(j==4) cell.setCellValue(((BoardMasterVO)bbsMasterCastList.get(i)).getBbsTyCodeNm()); //게시판유형
  			        	if(j==5) cell.setCellValue(((BoardMasterVO)bbsMasterCastList.get(i)).getUseAtTxt()); //사용여부
  			        	if(j==6) cell.setCellValue(((BoardMasterVO)bbsMasterCastList.get(i)).getFrstRegisterPnttm()); //생성일
  				 	}
  		        }
  			}
  	    response.setHeader("Set-Cookie", "fileDownload=true; path=/");
  		SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat ( "yyyy_MM_dd_HH_mm_ss", Locale.KOREA );
  		Date currentTime = new Date ();
  		String mTime = mSimpleDateFormat.format ( currentTime );
  		fileName = fileName+"("+mTime+")";
  		
  		response.setHeader("Content-Disposition", String.format("attachment; filename=\""+new String((fileName).getBytes("KSC5601"),"8859_1")+".xlsx"));
  		wb.write(response.getOutputStream());
  	    
  		}catch(Exception e) {
  			response.setHeader("Set-Cookie", "fileDownload=false; path=/");
  			response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
  			response.setHeader("Content-Type","text/html; charset=utf-8");
  			OutputStream out = null;
  			try {
  				out = response.getOutputStream();
  				byte[] data = new String("fail..").getBytes();
  				out.write(data, 0, data.length);
  			} catch(Exception ignore) {
  				ignore.printStackTrace();
  			} finally {
  				if(out != null) try { out.close(); } catch(Exception ignore) {}
  			}
  		}finally {
  			// 디스크 적었던 임시파일을 제거합니다.
  			wb.dispose();
  			try { wb.close(); } catch(Exception ignore) {}
  		}
  	}

}
