package com.eactive.eai.rms.onl.apim.portalnotice;

import com.eactive.apim.portal.file.entity.FileDetail;
import com.eactive.apim.portal.file.entity.FileInfo;
import com.eactive.apim.portal.file.service.FileService;
import com.eactive.apim.portal.file.service.FileTypeContext;
import com.eactive.apim.portal.portalNotice.entity.PortalNotice;
import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.data.entity.onl.apim.portalnotice.PortalNoticeService;
import com.eactive.eai.rms.data.entity.onl.apim.portalnotice.PortalNoticeUISearch;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

@Service
@Transactional(transactionManager = "transactionManagerForEMS")
public class PortalNoticeManService extends BaseService {
	private final PortalNoticeService portalNoticeService;
	private final PortalNoticeUIMapper portalNoticeUIMapper;
	private final FileService fileService;

	private String decodeString(String value) {
//		return new String(value.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
		return new String(value.getBytes(Charset.defaultCharset()), StandardCharsets.UTF_8);
	}

	@Autowired
	public PortalNoticeManService(PortalNoticeService portalNoticeService,
								  PortalNoticeUIMapper portalNoticeUIMapper,
								  FileService fileService){
		this.portalNoticeService = portalNoticeService;
		this.portalNoticeUIMapper = portalNoticeUIMapper;
		this.fileService = fileService;
	}


	public Page<PortalNoticeUI> selectList(Pageable pageable, PortalNoticeUISearch portalNoticeUISearch) {
		return portalNoticeService.findAll(pageable, portalNoticeUISearch)
				.map(portalNotice -> {
					PortalNoticeUI ui = portalNoticeUIMapper.toVo(portalNotice);
					setFileInfo(portalNotice, ui);
					return ui;
				});
	}

	private void setFileInfo(PortalNotice portalNotice, PortalNoticeUI ui) {
		if (StringUtils.isBlank(portalNotice.getFileId())) {
			ui.setHasAttachment(false);
			return;
		}

		FileInfo fileInfo = fileService.findById(portalNotice.getFileId());

		if (fileInfo == null || fileInfo.getFileDetails().isEmpty()) {
			ui.setHasAttachment(false);
		} else {
			FileDetail fileDetail = fileInfo.getFileDetails().get(0);
			String fileNames = fileDetail.getOriginalFileName() + "." + fileDetail.getFileExtension();
			ui.setFileName(fileNames);
			ui.setHasAttachment(true);
			ui.setFileInfo(fileInfo);
		}
	}

	public PortalNoticeUI selectDetail(String id) {
		PortalNotice portalNotice = portalNoticeService.getById(id);
		portalNotice.setReadCount(portalNotice.getReadCount() + 1);

		PortalNoticeUI ui = portalNoticeUIMapper.toVo(portalNotice);
		setFileInfo(portalNotice, ui);
		return ui;
	}

	public void insert(PortalNoticeUI portalNoticeUI) throws IOException {
		portalNoticeUI.setNoticeSubject(decodeString(portalNoticeUI.getNoticeSubject()));
		portalNoticeUI.setNoticeDetail(decodeString(StringEscapeUtils.unescapeHtml(portalNoticeUI.getNoticeDetail())));

		PortalNotice portalNotice = portalNoticeUIMapper.toEntity(portalNoticeUI);
		portalNotice.setId(null);
		portalNotice.setReadCount(0L);

		if (portalNoticeUI.getFiles() != null && !portalNoticeUI.getFiles().isEmpty()) {
			handleFileUpload(portalNoticeUI, portalNotice);
		}

		portalNoticeService.save(portalNotice);
	}

	private void handleFileUpload(PortalNoticeUI portalNoticeUI, PortalNotice portalNotice) throws IOException {
		MultipartFile file = portalNoticeUI.getFiles();

		if (file != null && !file.isEmpty()) {  // 새로운 파일이 업로드된 경우에만 처리
			String decodedFileName = decodeString(portalNoticeUI.getFileName());
			FileTypeContext.setFileType("notice");
			FileInfo fileInfo = fileService.createOrUpdateSingleFile(portalNotice.getFileId(), file, decodedFileName);

			if (fileInfo != null) {
				portalNotice.setFileId(fileInfo.getFileId());
			}
		}

	}

	public void update(PortalNoticeUI portalNoticeUI) throws IOException {
		portalNoticeUI.setNoticeSubject(decodeString(portalNoticeUI.getNoticeSubject()));
 		portalNoticeUI.setNoticeDetail(decodeString(StringEscapeUtils.unescapeHtml(portalNoticeUI.getNoticeDetail())));

		PortalNotice portalNotice = portalNoticeService.getById(portalNoticeUI.getId());

		if (portalNoticeUI.getFiles() != null && !portalNoticeUI.getFiles().isEmpty()) {
			handleFileUpload(portalNoticeUI, portalNotice);
		} else if (portalNoticeUI.isFileDeleted() && StringUtils.isNotBlank(portalNotice.getFileId()))  {
				fileService.deleteFile(portalNotice.getFileId());
				portalNotice.setFileId(null);
		}

		portalNoticeUIMapper.updateToEntity(portalNoticeUI, portalNotice);
		portalNoticeService.save(portalNotice);
	}

	public void delete(String id) {
		PortalNotice portalNotice = portalNoticeService.getById(id);
		Optional.ofNullable(portalNotice.getFileId()).ifPresent(fileService::deleteFile);
		portalNoticeService.deleteById(id);
	}

}
