package kcg.faics.report.service.impl;

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

import javax.annotation.Resource;

import kcg.faics.cmmn.egov.file.EgovFileMngUtil;
import kcg.faics.cmmn.egov.vo.FileVO;
import kcg.faics.report.service.ReportFileService;
import kcg.faics.report.service.ReportService;
import kcg.faics.report.vo.ReportFileVO;
import kcg.faics.report.vo.ReportVO;

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

import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl;

@Service("reportFileService")
public class ReportFileServiceImpl extends EgovAbstractServiceImpl implements ReportFileService {

	/**
	 * 견문 파일 시퀀스당 저장될 견문의 최대 갯수 
	 */
	private static final int SEQCNTLIMIT = 1000;

	/**
	 * 견문 관련 파일 Mapper 클래스.
	 */
	@Resource(name = "reportFileMapper")
	private ReportFileMapper reportFileMapper;

	/**
	 * 견문 관련 인터페이스.
	 */
	@Resource(name = "reportService")
	private ReportService reportService;
	
    /**
	 * 전자정부프레임워크에서 제공되는 파일 업로드 처리 관련 Utility.
	 **/
	@Resource(name = "EgovFileMngUtil")
	private EgovFileMngUtil fileUtil;
	
	@Override
	public int insertAndSaveFiles(final ReportVO dataVO, final Map<String, MultipartFile> fileMap) throws Exception {
		int result = 1;
		ReportVO originVO = reportService.select(dataVO);
		List<String> deleteFiles = new ArrayList<String>();
		
		if (fileMap != null) {

			if (dataVO.getInFsseq() <= 0) {
				dataVO.setInFsseq(selectFileSeq());	
			}
			if (dataVO.getInFsseq() <= 0) {
				throw new Exception();
			}
			
			List<FileVO> files = fileUtil.parseFileInf(fileMap, null, 0, "", FILE_PATH_KEYWORD, String.valueOf(dataVO.getInFsseq()));
			
			for (FileVO file : files) {
				if ("fileObj1".equalsIgnoreCase(file.getFileSn())) {
					dataVO.setInFile1(file.getStreFileNm());
					
					if (StringUtils.isNotBlank(originVO.getInFile1())) {
						deleteFiles.add("1");
					}
				} else if ("fileObj2".equalsIgnoreCase(file.getFileSn())) {
					dataVO.setInFile2(file.getStreFileNm());
					
					if (StringUtils.isNotBlank(originVO.getInFile2())) {
						deleteFiles.add("2");
					}
				} else if ("fileObj3".equalsIgnoreCase(file.getFileSn())) {
					dataVO.setInFile3(file.getStreFileNm());
					
					if (StringUtils.isNotBlank(originVO.getInFile3())) {
						deleteFiles.add("3");
					}
				} else if ("fileObj4".equalsIgnoreCase(file.getFileSn())) {
					dataVO.setInFile4(file.getStreFileNm());
					
					if (StringUtils.isNotBlank(originVO.getInFile4())) {
						deleteFiles.add("4");
					}
				} else if ("fileObj5".equalsIgnoreCase(file.getFileSn())) {
					dataVO.setInFile5(file.getStreFileNm());
					
					if (StringUtils.isNotBlank(originVO.getInFile5())) {
						deleteFiles.add("5");
					}
				}
			}
			if (deleteFiles.size() > 0) {
				result = deleteAndRemoveFiles(dataVO, deleteFiles.toArray(new String[deleteFiles.size()]));
			}
			
			result = reportFileMapper.insertFile(dataVO);
			if (result != 0) {
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("cnt", files.size());
				map.put("fsseq", dataVO.getInFsseq());
				result = reportFileMapper.updateFileSeq(map);
			}
			
			if (result == 0) {
				throw new Exception();
			}
		}
		return result;
	}

	@Override
	public int deleteAndRemoveFiles(final ReportVO dataVO, final String[] deleteFiles) throws Exception {
		ReportVO reportVO = reportService.select(dataVO);
		String fsSeq = String.valueOf(dataVO.getInFsseq());
		int deletedCnt = 0;
		
		if (dataVO.getInFsseq() <= 0) {
			return 0;
		}
		
		for (String idx : deleteFiles) {
			if (idx.equals("1")) {
				reportVO.setInFile1("");
				fileUtil.deleteFile(dataVO.getInFile1(), FILE_PATH_KEYWORD, fsSeq);
				deletedCnt++;
			}
			if (idx.equals("2")) {
				reportVO.setInFile2("");
				fileUtil.deleteFile(dataVO.getInFile2(), FILE_PATH_KEYWORD, fsSeq);
				deletedCnt++;
			}
			if (idx.equals("3")) {
				reportVO.setInFile3("");
				fileUtil.deleteFile(dataVO.getInFile3(), FILE_PATH_KEYWORD, fsSeq);
				deletedCnt++;
			}
			if (idx.equals("4")) {
				reportVO.setInFile4("");
				fileUtil.deleteFile(dataVO.getInFile4(), FILE_PATH_KEYWORD, fsSeq);
				deletedCnt++;
			}
			if (idx.equals("5")) {
				reportVO.setInFile5("");
				fileUtil.deleteFile(dataVO.getInFile5(), FILE_PATH_KEYWORD, fsSeq);
				deletedCnt++;
			}
		}

		int result = reportFileMapper.updateFile(reportVO);
		
		if (result > 0) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("cnt", (-deletedCnt));
			map.put("fsseq", fsSeq);
			result = reportFileMapper.updateFileSeq(map);
		}
		
		return result;
	}

	@Override
	public int selectFileSeq() throws Exception {
		int result = 0;
		
		ReportFileVO rptFileVO = reportFileMapper.selectFileSeq();
		int seq = rptFileVO.getFsSeq();
		int cnt = rptFileVO.getFsFileCount();
		
		if (seq == 0 || cnt > SEQCNTLIMIT) {
			seq = reportFileMapper.insertFileSeq();
		}
		
		if (seq > 0) {
			result = seq;
		} else {
			throw new Exception();
		}
		return result;
	}

}
