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

import kr.co.uplus.ez.api.homeMgt.dto.*;
import kr.co.uplus.ez.common.data.ApiResponseCode;
import kr.co.uplus.ez.common.data.Paging;
import kr.co.uplus.ez.common.utils.DateUtils;
import kr.co.uplus.ez.common.utils.FileIoUtils;
import kr.co.uplus.ez.common.utils.FileUtil;

import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


@Service
public class HomeMgtService {

	private static final Logger logger = LoggerFactory.getLogger(HomeMgtService.class);

	@Autowired
	@Qualifier("sqlSessionTemplateDb1")
	private SqlSessionTemplate sqlSessionMaster;

	@Autowired
	@Qualifier("sqlSessionTemplateDb2")
	private SqlSessionTemplate sqlSessionSlave;
	
	@Value("${file-resource.info.notice.path:/efs/admin/notice/}")
	private String noticeFilePath;

	/**
	 * date : 2022. 10. 18.
	 * auth : kjh
	 * desc : 공지사항 목록 조회
	 * @param noticeListReqDto
	 * @return NoticeListResDto
	 */
	public NoticeListResDto noticeList(NoticeListReqDto noticeListReqDto) {

		HomeMgtMapper homeMgtMapper = sqlSessionSlave.getMapper(HomeMgtMapper.class);
		
		String nowPage = String.valueOf(noticeListReqDto.getPage());
		int totalCnt = homeMgtMapper.selectNoticeTotalCnt(noticeListReqDto);


		if(totalCnt == 0) {
			Paging paging = new Paging();
			paging.setPage(nowPage);
			paging.setTotalCnt(String.valueOf(totalCnt));
			NoticeListRes NoticeListRes = new NoticeListRes();
			NoticeListRes.setList(new ArrayList<>());
			NoticeListRes.setPaging(paging);
			return new NoticeListResDto(ApiResponseCode.CM_NOT_FOUND, NoticeListRes);
		}

		int page = noticeListReqDto.getPage();
		int pagePerRows = noticeListReqDto.getPagePerRows();
		page = (page -1) * pagePerRows;
		noticeListReqDto.setPage(page);

		List<NoticeDto> noticeDto =  homeMgtMapper.selectNoticeList(noticeListReqDto);

		Paging paging = new Paging();
		paging.setPage(nowPage);
		paging.setTotalCnt(String.valueOf(totalCnt));

		NoticeListRes NoticeListRes = new NoticeListRes();
		NoticeListRes.setList(noticeDto);
		NoticeListRes.setPaging(paging);

		return new NoticeListResDto(ApiResponseCode.SUCCESS, NoticeListRes);
	}
	
	/**
	 * date : 2022. 10. 21.
	 * auth : kjh
	 * desc : 공지사항 목록 등록
	 * @param insertNoticeReqDto
	 * @return InsertNoticeResDto
	 */
	public InsertNoticeResDto insertNotice(InsertNoticeReqDto insertNoticeReqDto,  MultipartHttpServletRequest multipartRequest) {
		
		HomeMgtMapper homeMgtMapper = sqlSessionSlave.getMapper(HomeMgtMapper.class);
		
		List<MultipartFile> files = multipartRequest.getFiles("files");
		String yyyyMMddHHmmss = DateUtils.date2strYMDHMS();
		int NT_NO = 0;
		
		//공지사항 등록
		try {
			homeMgtMapper.insertNotice(insertNoticeReqDto);
			NT_NO = homeMgtMapper.insertNoticeNtNo();
		}catch(Exception e){
			e.printStackTrace();
			return new InsertNoticeResDto(ApiResponseCode.CM_DB_QUERY_ERR);
		}
		
		//공지사항 등록 완료시 파일 저장
		int idx = 1;
		String yyyyMMdd = DateUtils.date2strYMD();
		// Path : efs/admin/notice/yyyy/mm/
		String path = noticeFilePath + yyyyMMdd.substring(0, 4) + 
				  File.separator + yyyyMMdd.substring(4, 6) +
				  File.separator + yyyyMMdd.substring(6, 8);
		File dir = new File(path);
		if(!dir.isDirectory()) {
			dir.mkdirs();
		}
		
		try {
			for(int i=0; i<files.size(); i++){
				
				// NOTICE FILE UPLOAD.
				String ext = FileIoUtils.getExtension(files.get(i).getOriginalFilename());
				// File Nm : [reg_req_no]_[doc_no]_[doc_tp_cd].확장자
				String fileNm = yyyyMMddHHmmss + "_noticeFile_" + idx +"." + ext;
				String titleNm = files.get(i).getOriginalFilename();
				long fileSize = files.get(i).getSize();
				
				
				// File Upload.
				FileUtil.upload(files.get(i), fileNm, path);

				InsertNoticeFileDto insertNoticeFileDto = new InsertNoticeFileDto();
				insertNoticeFileDto.setBbsDivCd("02"); // 게시판 구분 코드 (01:일대일문의,02:공지사항,03:FAQ)
				insertNoticeFileDto.setBbsNo(NT_NO);
				insertNoticeFileDto.setFileNo(idx);
				insertNoticeFileDto.setFileTitle(titleNm);
				insertNoticeFileDto.setFileNm(fileNm);
				insertNoticeFileDto.setFileSize(fileSize);
				insertNoticeFileDto.setFilePath(path.replace("C:/Users/admin/git/hubez-admin/frontend/public", ""));
				insertNoticeFileDto.setRegId(insertNoticeReqDto.getRegId());
				insertNoticeFileDto.setChgId(insertNoticeReqDto.getRegId());
				
				homeMgtMapper.insertNoticeFile(insertNoticeFileDto);
				idx++;
			}
			
		}catch(Exception e) {
			return new InsertNoticeResDto(ApiResponseCode.CM_DB_QUERY_ERR);
		}
		
		
		return new InsertNoticeResDto(ApiResponseCode.SUCCESS);
	}
	
	/**
	 * date : 2022. 10. 24.
	 * auth : kjh
	 * desc : 공지사항 목록 수정
	 * @param updateNoticeReqDto
	 * @return UpdateNoticeResDto
	 */
	public UpdateNoticeResDto updateNotice(UpdateNoticeReqDto updateNoticeReqDto,  MultipartHttpServletRequest multipartRequest) {
		HomeMgtMapper homeMgtMapper = sqlSessionMaster.getMapper(HomeMgtMapper.class);
		
		List<MultipartFile> files = multipartRequest.getFiles("files");
		String yyyyMMddHHmmss = DateUtils.date2strYMDHMS();
		
		// 공지사항 수정
		try {
			homeMgtMapper.updateNotice(updateNoticeReqDto);
		} catch (Exception e) {
			return new UpdateNoticeResDto(ApiResponseCode.CM_DB_QUERY_ERR);
		}
		
		// 공지사항 수정 완료시 파일 저장
		int idx = homeMgtMapper.updateNoticeFileMaxNum(updateNoticeReqDto); // 해당 게시물의 최상위 파일 번호 + 1을 가져온다.
		String yyyyMMdd = DateUtils.date2strYMD(); // Path : efs/admin/notice/yyyy/mm/
		String path = noticeFilePath + yyyyMMdd.substring(0, 4) + 
					  File.separator + yyyyMMdd.substring(4, 6) +
					  File.separator + yyyyMMdd.substring(6, 8);
		File dir = new File(path);
		if(!dir.isDirectory()) dir.mkdirs(); // dir 생성
		
		try {
			for(int i=0; i<files.size(); i++){
				
				// NOTICE FILE UPLOAD.
				String ext = FileIoUtils.getExtension(files.get(i).getOriginalFilename());
				// File Nm : [reg_req_no]_[doc_no]_[doc_tp_cd].확장자
				String fileNm = yyyyMMddHHmmss + "_noticeFile_" + idx +"." + ext;
				String titleNm = files.get(i).getOriginalFilename();
				long fileSize = files.get(i).getSize();
				
				
				// File Upload.
				FileUtil.upload(files.get(i), fileNm, path);

				InsertNoticeFileDto insertNoticeFileDto = new InsertNoticeFileDto();
				insertNoticeFileDto.setBbsDivCd("02"); // 게시판 구분 코드 (01:일대일문의,02:공지사항,03:FAQ)
				insertNoticeFileDto.setBbsNo(updateNoticeReqDto.getNtNo());
				insertNoticeFileDto.setFileNo(idx);
				insertNoticeFileDto.setFileTitle(titleNm);
				insertNoticeFileDto.setFileNm(fileNm);
				insertNoticeFileDto.setFileSize(fileSize);
				insertNoticeFileDto.setFilePath(path.replace("C:/Users/admin/git/hubez-admin/frontend/public", ""));
				insertNoticeFileDto.setRegId(updateNoticeReqDto.getChgId());
				insertNoticeFileDto.setChgId(updateNoticeReqDto.getChgId());
				
				homeMgtMapper.insertNoticeFile(insertNoticeFileDto);
				idx++;
			}
			
		}catch(Exception e) {
			return new UpdateNoticeResDto(ApiResponseCode.CM_DB_QUERY_ERR);
		}
		
		// 첨부파일 삭제
		
		if(!updateNoticeReqDto.getDelFileNo().isEmpty()) {
			String[] delFile = updateNoticeReqDto.getDelFileNo().split(",");
			for(int j=0; j<delFile.length; j++){
				DelNoticeReqDto delNoticeReqDto = new DelNoticeReqDto();
				delNoticeReqDto.setFileNo(Integer.parseInt(delFile[j]));
				delNoticeReqDto.setNtNo(updateNoticeReqDto.getNtNo());
				homeMgtMapper.delNoticeFile(delNoticeReqDto);
			}			
		}
		
		return new UpdateNoticeResDto(ApiResponseCode.SUCCESS);
	}
	
	/**
	 * date : 2022. 10. 21.
	 * auth : kjh
	 * desc : 공지사항 editor 이미지 등록시 URL 리턴
	 * @param insertNoticeFileDto
	 * @return FileResDto
	 */
	public FileResDto fileResDto(MultipartHttpServletRequest multipartRequest) {
		
		HomeMgtMapper homeMgtMapper = sqlSessionSlave.getMapper(HomeMgtMapper.class);
		
		List<MultipartFile> files = multipartRequest.getFiles("files");
		String yyyyMMddHHmmss = DateUtils.date2strYMDHMS();
		String yyyyMMdd = DateUtils.date2strYMD(); // Path : efs/admin/notice/yyyy/mm/
		String path = noticeFilePath + yyyyMMdd.substring(0, 4) + 
				  File.separator + yyyyMMdd.substring(4, 6) +
				  File.separator + yyyyMMdd.substring(6, 8);
		File dir = new File(path);
		String uploadFile = "";
		if(!dir.isDirectory()) dir.mkdirs(); // dir 생성
		
		try {
			for(int i=0; i<files.size(); i++){
				
				String ext = FileIoUtils.getExtension(files.get(i).getOriginalFilename());
				String fileNm = yyyyMMddHHmmss + "_noticeEditFile." + ext;
				// File Upload.
				FileUtil.upload(files.get(i), fileNm, path);
				uploadFile = path + File.separator  + fileNm;
			}
			
		}catch(Exception e) {
			return new FileResDto(ApiResponseCode.CM_DB_QUERY_ERR);
		}
		
		return new FileResDto(ApiResponseCode.SUCCESS, uploadFile);
	}
	
	/**
	 * date : 2022. 11. 02.
	 * auth : kjh
	 * desc : 공지사항 삭제
	 * @param deleteNoticeReqDto
	 * @return
	 */
	public DeleteNoticeResDto deleteNotice(DeleteNoticeReqDto deleteNoticeReqDto) {

		HomeMgtMapper homeMgtMapper = sqlSessionSlave.getMapper(HomeMgtMapper.class);

		try {
			homeMgtMapper.deleteNotice(deleteNoticeReqDto);
		} catch (Exception e) {
			return new DeleteNoticeResDto(ApiResponseCode.CM_DB_QUERY_ERR);
		}

		return new DeleteNoticeResDto(ApiResponseCode.SUCCESS);
	}
	
	/**
	 * date : 2022. 11. 03.
	 * auth : kjh
	 * desc : faq 목록 조회
	 * @param faqListReqDto
	 * @return FaqListResDto
	 */
	public FaqListResDto faqList(FaqListReqDto faqListReqDto) {

		HomeMgtMapper homeMgtMapper = sqlSessionSlave.getMapper(HomeMgtMapper.class);
		
		String nowPage = String.valueOf(faqListReqDto.getPage());
		int totalCnt = homeMgtMapper.selectFaqTotalCnt(faqListReqDto);


		if(totalCnt == 0) {
			Paging paging = new Paging();
			paging.setPage(nowPage);
			paging.setTotalCnt(String.valueOf(totalCnt));
			FaqListRes faqListRes = new FaqListRes();
			faqListRes.setList(new ArrayList<>());
			faqListRes.setPaging(paging);
			return new FaqListResDto(ApiResponseCode.CM_NOT_FOUND, faqListRes);
		}

		int page = faqListReqDto.getPage();
		int pagePerRows = faqListReqDto.getPagePerRows();
		page = (page -1) * pagePerRows;
		faqListReqDto.setPage(page);

		List<FaqDto> faqDto =  homeMgtMapper.selectFaqList(faqListReqDto);

		Paging paging = new Paging();
		paging.setPage(nowPage);
		paging.setTotalCnt(String.valueOf(totalCnt));

		FaqListRes faqListRes = new FaqListRes();
		faqListRes.setList(faqDto);
		faqListRes.setPaging(paging);

		return new FaqListResDto(ApiResponseCode.SUCCESS, faqListRes);
	}
	
	/**
	 * date : 2022. 11. 03.
	 * auth : kjh
	 * desc : FAQ 등록
	 * @param insertFaqReqDto
	 * @return InsertFaqResDto
	 */
	public InsertFaqResDto insertFaq(InsertFaqReqDto insertFaqReqDto) {
		
		HomeMgtMapper homeMgtMapper = sqlSessionSlave.getMapper(HomeMgtMapper.class);
				
		//공지사항 등록
		try {
			insertFaqReqDto.setFaqSbst(insertFaqReqDto.getFaqSbst().replaceAll("\\n", "<br />"));
			homeMgtMapper.insertFaq(insertFaqReqDto);
		}catch(Exception e){
			return new InsertFaqResDto(ApiResponseCode.CM_DB_QUERY_ERR);
		}
		
		return new InsertFaqResDto(ApiResponseCode.SUCCESS);
	}
	
	/**
	 * date : 2022. 11. 03.
	 * auth : kjh
	 * desc : FAQ 수정
	 * @param updateFaqReqDto
	 * @return UpdateFaqResDto
	 */
	public UpdateFaqResDto updateFaq(UpdateFaqReqDto updateFaqReqDto) {
		
		HomeMgtMapper homeMgtMapper = sqlSessionSlave.getMapper(HomeMgtMapper.class);
				
		//공지사항 수정
		try {
			updateFaqReqDto.setFaqSbst(updateFaqReqDto.getFaqSbst().replaceAll("\\n", "<br />"));
			homeMgtMapper.updateFaq(updateFaqReqDto);
		}catch(Exception e){
			return new UpdateFaqResDto(ApiResponseCode.CM_DB_QUERY_ERR);
		}
		
		return new UpdateFaqResDto(ApiResponseCode.SUCCESS);
	}
	
	/**
	 * date : 2022. 11. 03.
	 * auth : kjh
	 * desc : FAQ 삭제
	 * @param deleteFaqReqDto
	 * @return
	 */
	public DeleteFaqResDto deleteFaq(DeleteFaqReqDto deleteFaqReqDto) {

		HomeMgtMapper homeMgtMapper = sqlSessionSlave.getMapper(HomeMgtMapper.class);

		try {
			homeMgtMapper.deleteFaq(deleteFaqReqDto);
		} catch (Exception e) {
			return new DeleteFaqResDto(ApiResponseCode.CM_DB_QUERY_ERR);
		}

		return new DeleteFaqResDto(ApiResponseCode.SUCCESS);
	}
	
}
