package kcg.faics.tg.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import kcg.faics.cmmn.bbs.BaseBbsService;
import kcg.faics.cmmn.egov.file.EgovFileMngUtil;
import kcg.faics.cmmn.egov.vo.FileVO;
import kcg.faics.cmmn.service.CodeService;
import kcg.faics.tg.vo.DivMngSearchVO;
import kcg.faics.tg.vo.DivMngVO;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl;

/**
 * 외사분실운영현황 관련 비지니스로직.
 * 
 * @author kimnomin
 *
 */
@Service("divMngService")
public class DivMngServiceImpl extends EgovAbstractServiceImpl implements
		BaseBbsService<DivMngSearchVO, DivMngVO> {
	
	/**
	 * property 파일에서 읽은 저장 경로 키워드. 
	 */
	public static final String FILE_PATH_KEYWORD = "Target.divmng.fileStorePath";
	
    /**
	 * 전자정부프레임워크에서 제공되는 파일 업로드 처리 관련 Utility.
	 **/
	@Resource(name = "EgovFileMngUtil")
	private EgovFileMngUtil fileUtil;	
	
	/**
	 * 외사분실운영현황 Mapper 클래스.
	 */
	@Resource(name = "divMngMapper")
	private DivMngMapper divMngMapper;

	/**
	 * Place별 다음에 사용할 DS_NO를 반환한다.
	 * 
	 * @param divMngVO
	 *            외사분실운영현황 VO
	 * @return place별 최대 DS_NO+1
	 * @throws Exception
	 *             기본 예외 처리
	 */
	private int selectNextNo(final DivMngVO divMngVO) throws Exception {
		int result = 1;
		try {
			result = divMngMapper.selectMaxNo(divMngVO) + 1; 
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result; 
	}
	
	@Override
	public DivMngVO select(final DivMngVO dataVO) throws Exception {
		return divMngMapper.select(dataVO);
	}

	@Override
	public List<DivMngVO> selectListAll(final DivMngSearchVO searchVO)
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<DivMngVO> selectList(final DivMngSearchVO searchVO) throws Exception {
		if (CodeService.LIST_ALL_VAL.equalsIgnoreCase(searchVO.getPlace())) {
			searchVO.setPlace("");
		}
		return divMngMapper.selectList(searchVO);
	}

	@Override
	public int selectListCnt(final DivMngSearchVO searchVO) throws Exception {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int selectTotalCnt(final DivMngSearchVO searchVO) throws Exception {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public HashMap<String, Object> insert(final DivMngVO dataVO,
			final Map<String, MultipartFile> fileMap) throws Exception {
		HashMap<String, Object> map = new HashMap<String, Object>();
		int no = selectNextNo(dataVO);
		if (no > 0) {
			dataVO.setNo(no);
			
			List<FileVO> fileList = fileUtil.parseFileInf(fileMap, null, 0, "", FILE_PATH_KEYWORD);
			for (FileVO fileVO : fileList) {
				if ("fileImgObj".equalsIgnoreCase(fileVO.getFileSn())) {
					dataVO.setFileImg(fileVO.getStreFileNm());
				} else if ("file1obj".equalsIgnoreCase(fileVO.getFileSn())) {
					dataVO.setFile1(fileVO.getStreFileNm());
				} else if ("file2obj".equalsIgnoreCase(fileVO.getFileSn())) {
					dataVO.setFile2(fileVO.getStreFileNm());
				} else if ("file3obj".equalsIgnoreCase(fileVO.getFileSn())) {
					dataVO.setFile3(fileVO.getStreFileNm());
				}
			}
			
			map.put("result", divMngMapper.insert(dataVO));
		} else {
			map.put("result", 0);
		}
		
		return map;
	}

	/**
	 * Update시 파일삭제 대상을 판별한다.
	 * 
	 * @param fileMap 파일 Map 객체
	 * @param fileMapKey 파일 Map 객체에서 추출할 key
	 * @param deleteFileList 삭제대상 목록
	 * @param deleteFileListKey 삭제대상 목록에서 추출할 문자열
	 * @return 파일삭제여부
	 */
	private boolean isRemoveTarget(final Map<String, MultipartFile> fileMap,
			final String fileMapKey, final List<String> deleteFileList,
			final String deleteFileListKey) {
		boolean isRemoveTarget = false;
		
		if (deleteFileList.contains(deleteFileListKey)
				|| (fileMap.containsKey(fileMapKey) && fileMap.get(fileMapKey).getSize() > 0)) {
			isRemoveTarget = true;
		}
		
		return isRemoveTarget;
	}
	
	@Override
	public HashMap<String, Object> update(final DivMngVO dataVO,
			final Map<String, MultipartFile> fileMap, final String[] deleteFiles)
			throws Exception {
		DivMngVO vo = select(dataVO);
		dataVO.setFileImg(vo.getFileImg());
		dataVO.setFile1(vo.getFile1());
		dataVO.setFile2(vo.getFile2());
		dataVO.setFile3(vo.getFile3());
		
		List<String> deleteFileList = new ArrayList<String>();
		if (deleteFiles != null) {
			deleteFileList = Arrays.asList(deleteFiles);
		}
		if (isRemoveTarget(fileMap, "fileImgObj", deleteFileList, "fileImg")) {
			fileUtil.deleteFile(vo.getFileImg(), FILE_PATH_KEYWORD);
			dataVO.setFileImg("");
		}
		if (isRemoveTarget(fileMap, "file1obj", deleteFileList, "file1")) {
			fileUtil.deleteFile(vo.getFile1(), FILE_PATH_KEYWORD);
			dataVO.setFile1("");
		}
		if (isRemoveTarget(fileMap, "file2obj", deleteFileList, "file2")) {
			fileUtil.deleteFile(vo.getFile2(), FILE_PATH_KEYWORD);
			dataVO.setFile2("");
		}
		if (isRemoveTarget(fileMap, "file3obj", deleteFileList, "file3")) {
			fileUtil.deleteFile(vo.getFile3(), FILE_PATH_KEYWORD);
			dataVO.setFile3("");
		}
		
		List<FileVO> fileList = fileUtil.parseFileInf(fileMap, null, 0, "", FILE_PATH_KEYWORD);
		for (FileVO fileVO : fileList) {
			if ("fileImgObj".equalsIgnoreCase(fileVO.getFileSn())) {
				dataVO.setFileImg(fileVO.getStreFileNm());
			} else if ("file1obj".equalsIgnoreCase(fileVO.getFileSn())) {
				dataVO.setFile1(fileVO.getStreFileNm());
			} else if ("file2obj".equalsIgnoreCase(fileVO.getFileSn())) {
				dataVO.setFile2(fileVO.getStreFileNm());
			} else if ("file3obj".equalsIgnoreCase(fileVO.getFileSn())) {
				dataVO.setFile3(fileVO.getStreFileNm());
			}
		}
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("result", divMngMapper.update(dataVO));
		
		return map;
	}

	@Override
	public HashMap<String, Object> delete(final DivMngVO dataVO) throws Exception {
		DivMngVO vo = select(dataVO);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("result", divMngMapper.delete(dataVO));
		
		if (StringUtils.isNotBlank(vo.getFileImg())) {
			fileUtil.deleteFile(vo.getFileImg(), FILE_PATH_KEYWORD);
		}
		if (StringUtils.isNotBlank(vo.getFile1())) {
			fileUtil.deleteFile(vo.getFile1(), FILE_PATH_KEYWORD);
		}
		if (StringUtils.isNotBlank(vo.getFile2())) {
			fileUtil.deleteFile(vo.getFile2(), FILE_PATH_KEYWORD);
		}
		if (StringUtils.isNotBlank(vo.getFile3())) {
			fileUtil.deleteFile(vo.getFile3(), FILE_PATH_KEYWORD);
		}
		
		return map;
	}
}
