package kr.co.uplus.ez.api.homeMgt;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import kr.co.uplus.ez.api.homeMgt.dto.*;
import kr.co.uplus.ez.api.sendNumMgt.dto.DeleteNumberReqDto;
import kr.co.uplus.ez.api.sendNumMgt.dto.DeleteNumberResDto;
import kr.co.uplus.ez.common.components.ValidComponents;
import kr.co.uplus.ez.common.data.ApiResponseCode;
import kr.co.uplus.ez.common.utils.FileIoUtils;

@RestController
@RequestMapping(value = "/api/v1/bo/homeMgt")
public class HomeMgtController {
	private static final Logger logger = LoggerFactory.getLogger(HomeMgtController.class);

	@Autowired
	HomeMgtService homeService;

	@Autowired
	ValidComponents validComponents;

	/**
	 * date : 2022. 10. 18. auth : kjh desc : 공지사항 조회.
	 * 
	 * @param noticeListReqDto
	 * @return NoticeListResDto
	 */
	@ApiOperation(value = "/noticeList", notes = "공지사항 조회")
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "SUCESS") })
	@RequestMapping(value = "/noticeList", method = { RequestMethod.POST })
	@ResponseBody
	public NoticeListResDto noticeList(@RequestBody @Valid NoticeListReqDto noticeListReqDto,
			BindingResult bindingResult, HttpServletResponse response) {

		if (validComponents.validParameter(bindingResult)) {
			return new NoticeListResDto(ApiResponseCode.CM_PARAMETER_ERROR);
		}

		return homeService.noticeList(noticeListReqDto);
	}

	/**
	 * date : 2022. 10. 21. auth : kjh desc : 공지사항 등록.
	 * 
	 * @param insertNoticeReqDto
	 * @return InsertNoticeResDto
	 */
	@ApiOperation(value = "/insertNotice", notes = "공지사항 등록")
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "SUCESS") })
	@RequestMapping(value = "/insertNotice", method = { RequestMethod.POST })
	@ResponseBody
	public InsertNoticeResDto insertNotice(@RequestPart(value = "key") InsertNoticeReqDto insertNoticeReqDto,
			MultipartHttpServletRequest multipartRequest) {

		return homeService.insertNotice(insertNoticeReqDto, multipartRequest);
	}

	/**
	 * date : 2022. 10. 24. auth : kjh desc : 공지사항 수정.
	 * 
	 * @param updateNoticeReqDto
	 * @return UpdateNoticeResDto
	 */
	@ApiOperation(value = "/updateNotice", notes = "공지사항 수정")
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "SUCESS") })
	@RequestMapping(value = "/updateNotice", method = { RequestMethod.POST })
	@ResponseBody
	public UpdateNoticeResDto updateNotice(@RequestPart(value = "key") UpdateNoticeReqDto updateNoticeReqDto,
			MultipartHttpServletRequest multipartRequest) {

		return homeService.updateNotice(updateNoticeReqDto, multipartRequest);
	}
	
	/**
	 * date : 2022. 10. 24.
	 * auth : kjh 
	 * desc : 공지사항 삭제.
	 * @param deleteNoticeReqDto
	 * @return DeleteNoticeResDto
	 */
	@ApiOperation(value = "/deleteNotice", notes = "공지사항 삭제")
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "SUCESS") })
	@RequestMapping(value = "/deleteNotice", method = { RequestMethod.POST })
	@ResponseBody
	public DeleteNoticeResDto deleteNotice(@RequestBody @Valid DeleteNoticeReqDto deleteNoticeReqDto, BindingResult bindingResult) {
		if (validComponents.validParameter(bindingResult)) {
			return new DeleteNoticeResDto(ApiResponseCode.CM_PARAMETER_ERROR);
		}

		return homeService.deleteNotice(deleteNoticeReqDto);
	}

	/**
	 * date : 2022. 10. 24. auth : kjh desc : 공지사항 editor 이미지 업로드 후 링크 리턴.
	 * 
	 * @param updateNoticeReqDto
	 * @return UpdateNoticeResDto
	 */
	@ApiOperation(value = "/getImageUrl", notes = "공지사항 editor 이미지 업로드 후 링크 리턴")
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "SUCESS") })
	@RequestMapping(value = "/getImageUrl", method = { RequestMethod.POST })
	@ResponseBody
	public FileResDto fileResDto(MultipartHttpServletRequest multipartRequest) {
		
		return homeService.fileResDto(multipartRequest);
	}

	/**
	 * 파일 다운로드
	 * 
	 * @throws IOException
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("filedownload")
	public void filedownload(@RequestBody LinkedHashMap param, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		logger.debug(param.toString());

		File file = new File(param.get("filePath") + File.separator + param.get("fileNm"));

		if (file.exists()) {
			FileIoUtils.fileDownload(file, request, response);
		}
	}
	
	/**
	 * date : 2022. 11. 02. 
	 * auth : kjh 
	 * desc : 이미지 미리보기.
	 * @param imgurl
	 * @return imgurl
	 */
	@ApiOperation(value = "이미지 미리보기", notes = "이미지 미리보기")
	@GetMapping(value = "/preview/{imgurl}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
	public ResponseEntity<byte[]> previewImageResource(@PathVariable @ApiParam(value = "이미지 경로") String imgurl) {
		try {
			String imgurldec = URLDecoder.decode(imgurl);

			String imgurlreplace = imgurldec.replaceAll("\\|", "/");
			logger.debug("preview image imgurl={} imgurldecode={} imgurlreplace={}", imgurl, imgurldec, imgurlreplace);

			Path path = Paths.get(imgurlreplace);
			String contentType = Files.probeContentType(path);

			String fileNameOnly = imgurlreplace;
			String[] fileNameArr = imgurlreplace.split("/");
			if (fileNameArr != null && fileNameArr.length != 0)
				fileNameOnly = fileNameArr[fileNameArr.length - 1];

			HttpHeaders headers = new HttpHeaders();
			headers.setContentDisposition(
					ContentDisposition.builder("attachment").filename(fileNameOnly, StandardCharsets.UTF_8).build());
			headers.add(HttpHeaders.CONTENT_TYPE, contentType);

			byte[] b = Files.readAllBytes(path);

			return new ResponseEntity<byte[]>(b, headers, HttpStatus.OK);
		} catch (Exception e) {
			logger.error("imgurl err, e={}, e", e.getMessage());
			return new ResponseEntity<byte[]>(HttpStatus.NOT_FOUND);
		}
	}
	
	/**
	 * date : 2022. 11. 03. 
	 * auth : kjh 
	 * desc : FAQ 조회.
	 * @param faqListReqDto
	 * @return FaqListResDto
	 */
	@ApiOperation(value = "/faqList", notes = "FAQ 조회")
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "SUCESS") })
	@RequestMapping(value = "/faqList", method = { RequestMethod.POST })
	@ResponseBody
	public FaqListResDto faqList(@RequestBody @Valid FaqListReqDto faqListReqDto,
			BindingResult bindingResult, HttpServletResponse response) {

		if (validComponents.validParameter(bindingResult)) {
			return new FaqListResDto(ApiResponseCode.CM_PARAMETER_ERROR);
		}

		return homeService.faqList(faqListReqDto);
	}
	
	/**
	 * date : 2022. 11. 03. 
	 * auth : kjh 
	 * desc : FAQ 등록.
	 * @param insertFaqReqDto
	 * @return InsertFaqResDto
	 */
	@ApiOperation(value = "/insertFaq", notes = "FAQ 등록")
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "SUCESS") })
	@RequestMapping(value = "/insertFaq", method = { RequestMethod.POST })
	@ResponseBody
	public InsertFaqResDto insertFaq(@RequestBody @Valid InsertFaqReqDto insertFaqReqDto, BindingResult bindingResult) {
		
		System.out.println("insertFaqReqDto ::::" + insertFaqReqDto);
		
		if (validComponents.validParameter(bindingResult)) {
			return new InsertFaqResDto(ApiResponseCode.CM_PARAMETER_ERROR);
		}

		return homeService.insertFaq(insertFaqReqDto);
	}
	
	/**
	 * date : 2022. 11. 03. 
	 * auth : kjh 
	 * desc : FAQ 수정.
	 * @param updateFaqReqDto
	 * @return UpdateFaqResDto
	 */
	@ApiOperation(value = "/updateFaq", notes = "FAQ 수정")
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "SUCESS") })
	@RequestMapping(value = "/updateFaq", method = { RequestMethod.POST })
	@ResponseBody
	public UpdateFaqResDto updateFaq(@RequestBody @Valid UpdateFaqReqDto updateFaqReqDto, BindingResult bindingResult) {
				
		if (validComponents.validParameter(bindingResult)) {
			return new UpdateFaqResDto(ApiResponseCode.CM_PARAMETER_ERROR);
		}

		return homeService.updateFaq(updateFaqReqDto);
	}
	
	/**
	 * date : 2022. 11. 03.
	 * auth : kjh 
	 * desc : FAQ 삭제.
	 * @param deleteFaqReqDto
	 * @return DeleteFaqResDto
	 */
	@ApiOperation(value = "/deleteFaq", notes = "FAQ 삭제")
	@ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "SUCESS") })
	@RequestMapping(value = "/deleteFaq", method = { RequestMethod.POST })
	@ResponseBody
	public DeleteFaqResDto deleteFaq(@RequestBody @Valid DeleteFaqReqDto deleteFaqReqDto, BindingResult bindingResult) {
		if (validComponents.validParameter(bindingResult)) {
			return new DeleteFaqResDto(ApiResponseCode.CM_PARAMETER_ERROR);
		}

		return homeService.deleteFaq(deleteFaqReqDto);
	}
}
