package com.madeu.service.common.file.impl;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.madeu.constants.Constants;
import com.madeu.dao.web.webuser.WebUserSqlMapDAO;
import com.madeu.service.common.file.FileService;
import com.madeu.util.FileDownloadUtil;
import com.madeu.util.FileStoreUtil;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("FileService")
public class FileServiceImpl  implements FileService{
	
	@Autowired
	private WebUserSqlMapDAO webUserSqlMapDAO;
	
	@Value("${file.upload-path}")
	String F_PATH;

	@Value("${url.cdn}")
	String CDN_URL;
	
	/**
	 * 파일 등록
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@Override
	public HashMap<String, Object> uploadFile(
			HashMap<String, Object> paramMap, MultipartFile file) throws Exception{
		log.debug("FileServiceImpl uploadFile START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		// folderName
		// UA : 고객 동의서 서명
		log.debug("type        :"+paramMap.get("type"));

		// V : 동영상
		// I : 이미지
		// F : 첨부파일 ("gif","png","jpg","jpeg","doc","docx","xls","xlsx","hwp","hwpx","pdf","ppt","pptx")
		// P : 첨부파일 ("gif","png","jpg","jpeg","pdf")
		log.debug("fileType    :"+paramMap.get("fileType"));
		
		// 선택
		// summernote 여부
		log.debug("summernoteYn:"+paramMap.get("summernoteYn"));
		
		try{
			
			boolean check  = true;
			
			if(null==paramMap.get("fileType")||("").equals(paramMap.get("fileType"))){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","파일 종류 정보가 없습니다.");
				
			}
			
			if(null==paramMap.get("type")||("").equals(paramMap.get("type"))){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","파일 유형 정보가 없습니다.");
				
			}else {
				String type = String.valueOf(paramMap.get("type"));
				
				if(("UA").equals(type)) {
					paramMap.put("folderName","useragreement");
				}
				else if(("CI").equals(type)) {
					paramMap.put("folderName","categoryItem");
				}
				else if(("EI").equals(type)){
					paramMap.put("folderName","appeventbanner");
				}
				else if(("SI").equals(type)){
					paramMap.put("folderName","appcontentthumbnail");
				}
				else if(("CDI").equals(type)){
					paramMap.put("folderName","contentdetail");
				}
				else if(("WMB").equals(type)){
					paramMap.put("folderName","mainbanner");
				}
				else if(("WP").equals(type)){
					paramMap.put("folderName","popup");
				}
				else if(("WE").equals(type)){
					paramMap.put("folderName","event");
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc","등록 가능한 파일 유형이 아닙니다.");
				}
			}
			
			if(check == true){
				String filename = file.getOriginalFilename();
				String ext      = filename.substring(filename.lastIndexOf(".")+1,filename.length()).toLowerCase();
				String fileType = String.valueOf(paramMap.get("fileType"));
				String path = "";
				
				if(("V").equals(fileType)){
					map = FileStoreUtil.checkAppFileVideo(file, true);
					check = (Boolean) map.get("check");
					path = paramMap.get("folderName")+"/video";
					ext = "mp4";
				}
				else if(("I").equals(fileType)){
					map = FileStoreUtil.checkAppFileImage(file, true);
					check = (Boolean) map.get("check");
					path = paramMap.get("folderName")+"/image";
					ext = "jpg";
				}
				else if(("F").equals(fileType)){
					map = FileStoreUtil.checkAppFile(file, true);
					check = (Boolean) map.get("check");
					path = paramMap.get("folderName")+"/image";
				}
				else if(("P").equals(fileType)){
					map = FileStoreUtil.checkAppFile2(file, true);
					check = (Boolean) map.get("check");
					path = paramMap.get("folderName")+"/image";
				}
				else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc","등록 가능한 파일이 아닙니다.");
				}
				
				if(true == check){
					if(file != null&&file.getSize()>0){
						String folderName = String.valueOf(paramMap.get("folderName"));
						String fullFolderName = path;
						
						String url = "";
						if(("F").equals(fileType)||("P").equals(fileType)){
							map = FileStoreUtil.saveAttachments(fullFolderName, file);

							map.put("cdnUrl", CDN_URL);
							
						}else {
							String summernoteYn = String.valueOf(paramMap.get("summernoteYn"));
							
							HashMap<String, Object> fileMap = new HashMap<String, Object>();
							if(("Y").equals(summernoteYn)){
								fileMap = FileStoreUtil.saveFile(fullFolderName, file, ext, "summernoteImage/");
								
							}else {
								fileMap = FileStoreUtil.saveFile(fullFolderName, file, ext, "");
							}
							
							log.debug("url  :"+url);
							
							map.put("msgCode", Constants.OK);
							map.put("success","true");
							map.put("cdnUrl", CDN_URL);
							map.put("fileUrl", fileMap.get("path"));
							map.put("fileName", fileMap.get("fileName"));
						}
					}
				}else{
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc", map.get("msgDesc"));
				}
			}
			
		}catch(Exception e){
			map.put("msgCode", Constants.FAIL);
			map.put("msgDesc", map.get("msgDesc"));
			throw new Exception(e.getMessage());
		}
		
		log.debug("FileServiceImpl uploadFile END");
		return map;
	}
	
	/**
	 * 파일 다운로드
	 * 
	 * 
	 * @param paramMap
	 * @return
	 * @throws MipleException 
	 */
	@Override
	public HashMap<String, Object> downloadFile(HashMap<String, Object> paramMap,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.debug("FileServiceImpl downloadFile START");
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		log.debug("selectId          :"+paramMap.get("selectId"));
		
		// folderName
		// UA : 고객 동의서 서명
		log.debug("type              :"+paramMap.get("type"));
		
		try{
			boolean check  = true;
			
			if(null==paramMap.get("selectId")||("").equals(paramMap.get("selectId"))){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","파일 식별자 정보가 없습니다.");
			}
			
			if(null==paramMap.get("type")||("").equals(paramMap.get("type"))){
				check = false;
				map.put("msgCode", Constants.FAIL);
				map.put("msgDesc","파일 유형 정보가 없습니다.");
				
			}
			
			if(check == true){
				List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();
				
				String type = String.valueOf(paramMap.get("type"));
				
				if(("UA").equals(type)) {
					// 고객 동의서 서명
					paramMap.put("muUserAgreementId", paramMap.get("selectId"));
					listMap = webUserSqlMapDAO.selectUserAgreementFile(paramMap);
					
					if(listMap.size()==1) {
						String defaultPath = F_PATH.trim();
						
						String filePath    = String.valueOf(listMap.get(0).get("filePath"));
						String oFileName   = String.valueOf(listMap.get(0).get("orgFileName"));
						
						filePath = defaultPath.concat(filePath);
						
						FileDownloadUtil.fileDownload(request, response, filePath, oFileName);
						
						map.put("msgCode", Constants.OK);
						map.put("success", true);
					}else {
						map.put("msgCode", Constants.FAIL);
						map.put("success", false);
						map.put("msgDesc","파일 정보가 없습니다.");
					}
				}else {
					check = false;
					map.put("msgCode", Constants.FAIL);
					map.put("msgDesc","다운로드 가능한 파일 유형이 아닙니다.");
				}
			}
		}catch(Exception e){
			map.put("msgCode", Constants.FAIL);
			map.put("success", false);
			
			throw new Exception(e.getMessage());
		}
		
		log.debug("FileServiceImpl downloadFile END");
		return map;
	}
}
