package com.style24.front.biz.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.MetadataException;
import com.drew.metadata.exif.ExifIFD0Directory;
import com.gagaframework.web.util.GagaFileUploadUtil;
import com.gagaframework.web.util.GagaFileUtil;
import com.gagaframework.web.util.GagaUploadedFileInfo;
import com.style24.core.biz.service.TscOrderService;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.front.biz.service.TsfCommonService;
import com.style24.front.support.controller.TsfBaseController;
import com.style24.front.support.security.session.TsfSession;
import com.style24.persistence.domain.Order;

import lombok.extern.slf4j.Slf4j;

/**
 * 공통 Controller
 *
 * @author gagamel
 * @since 2021. 2. 19
 */
@Controller
@RequestMapping("/common")
@Slf4j
public class TsfCommonController extends TsfBaseController {
	
	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private Environment env;
	
	@Autowired
	private TscOrderService coreOrderService;
	
	@Autowired
	private TsfCommonService commonService;

	@Value("${upload.default.target.path}")
	private String uploadTargetPath;

	/**
	 * Download a file
	 *
	 * @param request - HttpServletRequest
	 * @param downloadFile - 다운로드할 파일
	 * @return
	 * @throws IOException
	 * @author gagamel
	 * @since 2019. 12. 6
	 */
	@GetMapping("/file/download")
	@ResponseBody
	public ResponseEntity<InputStreamResource> downloadFile(HttpServletRequest request, @RequestParam("downloadFile") String downloadFile) throws IOException {
		String fileName = StringUtils.replace(downloadFile, "../", "");
		log.debug("fileName: {}", fileName);

		String downloadPath = env.getProperty("download.path");
		log.debug("downLoadPath :{}", downloadPath);

		String fileNameWithPath = GagaFileUtil.getConcatenationPath(downloadPath, fileName);
		log.debug("fileNameWithPath: {}", fileNameWithPath);

		return GagaFileUtil.writeFile(request, fileNameWithPath);
	}

	/**
	 * Upload a file
	 *
	 * @param subDir - 업로드 하위 디렉토리
	 * @param policy - 업로드 정책
	 * @param file - MultipartFile
	 * @return 업로드한 파일의 정보
	 * @throws IOException
	 * @author gagamel
	 * @throws ImageProcessingException 
	 * @throws MetadataException 
	 * @since 2019. 12. 6
	 */
	@PostMapping("/file/upload")
	@ResponseBody
	public GagaUploadedFileInfo uploadFile(@RequestParam(value = "subDir") String subDir, @RequestParam(value = "policy", required = false) String policy, MultipartFile file) throws IOException, ImageProcessingException, MetadataException {
		if (StringUtils.isEmpty(policy)) {
			policy = "default";
		}
//		2021-10-19 김유중 : 이미지 중복 생성 제거 (root,filepat)
//		int orientation = 1;
//		Metadata metadata = ImageMetadataReader.readMetadata(convert(file));
//
//		Directory directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
//		if(directory != null) {
//			orientation = directory.getInt(ExifIFD0Directory.TAG_ORIENTATION);
//		}
//
//		log.info("orientation: {}", orientation);
		String targetPath = GagaFileUtil.getConcatenationPath(env.getProperty("upload." + policy + ".target.path"), subDir);

		GagaFileUploadUtil fuUtil = new GagaFileUploadUtil(targetPath, Long.parseLong(env.getProperty("upload." + policy + ".max.size")), env.getProperty("upload." + policy + ".allow.extension"), env.getProperty("upload." + policy + ".view"));

		GagaUploadedFileInfo ufInfo = fuUtil.uploadFile(file);
//		if (!"excel".equals(policy)) {
//			// 운영서버에서만 FTP로 파일 업로드
//			String profiles = env.getProperty("spring.profiles.active").toLowerCase();
//			if ("run".equals(profiles) || "locp".equals(profiles)) {
//				GagaFtpUtil ftpUtil = new GagaFtpUtil(env.getProperty("speedy.ftp.host"), env.getProperty("speedy.ftp.port"), env.getProperty("speedy.ftp.username"), env.getProperty("speedy.ftp.pwd"));
//
//				File srcFile = new File(GagaFileUtil.getConcatenationPath(targetPath, ufInfo.getNewFileName()));
//				ftpUtil.upload(srcFile, "/" + subDir);
//				ftpUtil.close();
//			}
//		}
		return ufInfo;
	}
	
	public File convert(MultipartFile multipartFile) throws IOException {
		File file = new File(multipartFile.getOriginalFilename());
		file.createNewFile();
		FileOutputStream fos = new FileOutputStream(file);
		fos.write(multipartFile.getBytes());
		fos.close();
		return file;
	}

	

	/**
	 * Delete a file
	 *
	 * @param subDir - 업로드 하위 디렉토리
	 * @param fileNm - 파일명
	 * @return
	 * @throws IOException
	 * @author sasa004
	 * @since 2020. 04. 06
	 */
	@PostMapping("/file/delete")
	@ResponseBody
	public void deleteFile(@RequestParam(value = "subDir") String subDir, @RequestParam(value = "fileNm", required = false) String fileNm) throws IOException {
		String targetPath = GagaFileUtil.getConcatenationPath(env.getProperty("upload.default.target.path"), subDir);

		GagaFileUtil.deleteFile(GagaFileUtil.getConcatenationPath(targetPath, fileNm));

//		// 운영서버이면 FTP 파일 삭제
//		String profiles = env.getProperty("spring.profiles.active").toLowerCase();
//		if ("run".equals(profiles) || "locp".equals(profiles)) {
//			GagaFtpUtil ftpUtil = new GagaFtpUtil(env.getProperty("speedy.ftp.host"), env.getProperty("speedy.ftp.port"), env.getProperty("speedy.ftp.username"), env.getProperty("speedy.ftp.pwd"));
//			log.debug("targetPath : " + targetPath);
//			ftpUtil.delete("/" + subDir, fileNm);
//			ftpUtil.close();
//		}
	}

	/**
	 * Upload files
	 *
	 * @param subDir - 업로드 하위 디렉토리
	 * @param files - MultipartFile List
	 * @return 업로드한 파일의 정보
	 * @throws IOException
	 * @author gagamel
	 * @since 2019. 12. 6
	 */
	@PostMapping("/files/upload")
	@ResponseBody
	public Collection<GagaUploadedFileInfo> uploadFiles(@RequestParam(value = "subDir") String subDir, List<MultipartFile> files) throws IOException {
		String targetPath = GagaFileUtil.getConcatenationPath(env.getProperty("upload.default.target.path"), subDir);
		GagaFileUploadUtil fuUtil = new GagaFileUploadUtil(targetPath);

		Collection<GagaUploadedFileInfo> ufList = fuUtil.uploadFiles(files);
		log.debug("ufList: {}", ufList);

//		// 운영서버에서만 FTP로 파일 업로드
//		String profiles = env.getProperty("spring.profiles.active").toLowerCase();
//		if ("run".equals(profiles) || "locp".equals(profiles)) {
//			if (ufList != null && !ufList.isEmpty()) {
//				GagaFtpUtil ftpUtil = new GagaFtpUtil(env.getProperty("speedy.ftp.host"), env.getProperty("speedy.ftp.port"), env.getProperty("speedy.ftp.username"), env.getProperty("speedy.ftp.pwd"));
//
//				for (GagaUploadedFileInfo ufInfo : ufList) {
//					File srcFile = new File(GagaFileUtil.getConcatenationPath(targetPath, ufInfo.getNewFileName()));
//					ftpUtil.upload(srcFile, "/" + subDir);
//				}
//
//				ftpUtil.close();
//			}
//		}

		return ufList;
	}

	/**
	 * 로그인 체크
	 *
	 * @return true:로그인, false:비로그인
	 * @author eskim
	 * @since 2021. 3. 08
	 */
	@GetMapping("/login/check")
	@ResponseBody
	public boolean checkLogin() {
		return TsfSession.isLogin();
	}
	
	
	/**
	 * 배송지정보변경팝업
	 *
	 * @param
	 * @return
	 * @author jsh77b
	 * @since 2021. 02. 17
	 */
	@ResponseBody
	@PostMapping(value = "/delvAddrChangePop")
	public ModelAndView delvAddrChangePop(Order order) {
		
		ModelAndView mav = new ModelAndView();
		
		// 1. 로그인체크 후 custNo 설정
		if (TsfSession.isLogin()) {
			order.setCustNo(TsfSession.getInfo().getCustNo()); // 고객번호등록
		} else {
			order.setCustNo(0);
		}
		
		// 1.0 주문고객 배송지정보조회
		Collection<Order> deliveryAddrList = coreOrderService.getDeliveryAddrInfo(order);
		int index 				= 0;
		int deliveryAddrCnt 	= deliveryAddrList.size();
		
		for (Order deliveryAddr : deliveryAddrList) {
			if (index == 0) {
				if (deliveryAddr.getRecipZipcode() == null || "".equals(deliveryAddr.getRecipZipcode())) {
					deliveryAddrCnt = 0;
				}
			}
		}
		
		mav.addObject("deliveryAddrList"	, deliveryAddrList);		// 배송지정보
		mav.addObject("deliveryAddrCnt"		, deliveryAddrCnt);			// 배송지등록수
		mav.setViewName(super.getDeviceViewName("popup/DelvAddrChangePop"));
		
		return mav;
	}
	
	/**
	 * 배송지정보수정팝업
	 *
	 * @param
	 * @return
	 * @author jsh77b
	 * @since 2021. 02. 17
	 */
	@ResponseBody
	@RequestMapping(value = "/delvAddrModifyPop")
	public ModelAndView delvAddrModifyPop(@RequestBody Order order) {
		
		ModelAndView mav = new ModelAndView();
		Order deliveryAddrInfo = new Order();
		
		// 2. 로그인체크 후 고객정보 설정
		if (TsfSession.isLogin()) {
			order.setCustNo(TsfSession.getInfo().getCustNo()); // 고객번호등록
			
			// 2.1 주문고객 배송지정보조회
			Collection<Order> deliveryAddrList = coreOrderService.getDeliveryAddrInfo(order);
			
			for (Order deliveryAddr : deliveryAddrList) {
				// 회원 배송지 번호가 존재하면 실행
				if (order.getCustDelvAddrSq() > 0) {
					if (order.getCustDelvAddrSq() == deliveryAddr.getCustDelvAddrSq()) {
						deliveryAddrInfo = deliveryAddr;
					}
				}
			}
		} 
		
		//deliveryAddrInfo.getRecipPhnno();
		
		mav.addObject("isLogin"			, TsfSession.isLogin());					// 로그인여부
		mav.addObject("deliveryAddrInfo", deliveryAddrInfo);						// 배송지정보
		mav.setViewName(super.getDeviceViewName("popup/DelvAddrModifyPop"));
		
		return mav;
	}
	
	/**
	 * 배송지정보수정
	 *
	 * @param
	 * @return
	 * @author jsh77b
	 * @since 2021. 02. 17
	 */
	@ResponseBody
	@PostMapping(value = "/updateCustDeliveryAddr")
	public String updateDeliveryAddr(@RequestBody Order order) {
		// 1. 로그인체크 후 custNo 설정
		if (TsfSession.isLogin()) {
			order.setCustNo(TsfSession.getInfo().getCustNo()); // 고객번호등록
		} else {
			order.setCustNo(0);
		}
		
		// recipPhnno '-' 처리
		order.setHypenRecipPhone();
		
		coreOrderService.updateCustDeliveryAddr(order);
		
		return message.getMessage("SUCC_0001");
	}
	
	/**
	 * 배송지정보추가팝업
	 *
	 * @param
	 * @return
	 * @author jsh77b
	 * @since 2021. 02. 17
	 */
	@ResponseBody
	@RequestMapping(value = "/delvAddrAddPop")
	public ModelAndView delvAddrAddPop(Order order) {
		
		ModelAndView mav = new ModelAndView();
		mav.addObject("isLogin"	, TsfSession.isLogin());					// 로그인여부
		mav.setViewName(super.getDeviceViewName("popup/DelvAddrAddPop"));

		return mav;
	}
	
	/**
	 * 배송지정보추가
	 *
	 * @param
	 * @return
	 * @author jsh77b
	 * @since 2021. 02. 17
	 */
	@ResponseBody
	@PostMapping(value = "/createCustDeliveryAddr")
	public int createDeliveryAddr(@RequestBody Order order) {
		// 1. 로그인체크 후 custNo 설정
		if (TsfSession.isLogin()) {
			order.setCustNo(TsfSession.getInfo().getCustNo()); // 고객번호등록
		} else {
			// 2021.09.13 card007 비회원은 TB_CUST_DELIVERY_ADDR에 등록하지 않는다.
			// order.setCustNo(0);
			return 0;
		}
		
		coreOrderService.createCustDeliveryAddr(order);
		
		int custDelvAddrSq = order.getCustDelvAddrSq();
		
		return custDelvAddrSq;
	}
	
	/**
	 * 배송지메모변경팝업
	 *
	 * @param
	 * @return
	 * @author jsh77b
	 * @since 2021. 02. 17
	 */
	@ResponseBody
	@RequestMapping(value = "/delvMemoChangePop")
	public ModelAndView delvMemoChangePop(@RequestBody Order order) {
		
		ModelAndView mav = new ModelAndView();
		
		mav.addObject("ordNo", order.getOrdNo() == null ? 0 : order.getOrdNo());
		
		mav.addObject("delvMemo"	, order.getDelvMemo());
		mav.setViewName(super.getDeviceViewName("popup/DelvMemoChangePop"));
		
		return mav;
	}
	
	/**
	 * 주문배송지정보수정
	 *
	 * @param
	 * @return
	 * @author jsh77b
	 * @since 2021. 04. 02
	 */
	@ResponseBody
	@PostMapping(value = "/updateDeliverAddr")
	public int updateDeliverAddr(@RequestBody Order order) {
		// 1. 로그인체크 후 custNo 설정
		if (TsfSession.isLogin()) {
			order.setCustNo(TsfSession.getInfo().getCustNo()); // 고객번호등록
		} else {
			order.setCustNo(0);
		}
		
		int rtn = commonService.updateDeliverAddr(order);
		
		return rtn;
	}
	
	/**
	 * 주문배송메모수정
	 *
	 * @param
	 * @return
	 * @author jsh77b
	 * @since 2021. 04. 02
	 */
	@ResponseBody
	@PostMapping(value = "/updateDeliverAddrDelvMemo")
	public int updateDeliverAddrDelvMemo(@RequestBody Order order) {
		// 1. 로그인체크 후 custNo 설정
		if (TsfSession.isLogin()) {
			order.setCustNo(TsfSession.getInfo().getCustNo()); // 고객번호등록
		} else {
			order.setCustNo(0);
		}
		
		int rtn = commonService.updateDeliverAddrDelvMemo(order);
		
		return rtn;
	}
	
	/**
	 * 배송지정등록 배송지등록수 체크
	 *
	 * @param
	 * @return
	 * @author jsh77b
	 * @since 2021. 08. 11
	 */
	@ResponseBody
	@PostMapping(value = "/addDelvAddrCnt")
	public int addDelvAddrCnt(Order order) {
		
		// 1. 로그인체크 후 custNo 설정
		if (TsfSession.isLogin()) {
			order.setCustNo(TsfSession.getInfo().getCustNo()); // 고객번호등록
		} else {
			order.setCustNo(0);
		}
		
		// 1.0 주문고객 배송지정보조회
		Collection<Order> deliveryAddrList = coreOrderService.getDeliveryAddrInfo(order);
		int index 				= 0;
		int deliveryAddrCnt 	= deliveryAddrList.size();
		
		for (Order deliveryAddr : deliveryAddrList) {
			if (index == 0) {
				if (deliveryAddr.getRecipZipcode() == null || "".equals(deliveryAddr.getRecipZipcode())) {
					deliveryAddrCnt = 0;
				}
			}
		}
		
		int rtn = deliveryAddrCnt;
		return rtn;
	}

}
