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

import com.eactive.apim.portal.file.entity.FileInfo;
import com.eactive.apim.portal.file.service.FileService;
import com.eactive.apim.portal.portaluser.entity.PortalUser;
import com.eactive.apim.portal.portaluser.entity.PortalUserEnums;
import com.eactive.apim.portal.qna.entity.Inquiry;
import com.eactive.apim.portal.user.entity.UserInfo;
import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.data.entity.man.user.UserInfoService;
import com.eactive.eai.rms.data.entity.onl.apim.portalinquiry.PortalInquirySearch;
import com.eactive.eai.rms.data.entity.onl.apim.portalinquiry.PortalInquiryService;
import com.eactive.eai.rms.onl.apim.masking.MaskingUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
@Transactional(transactionManager = "transactionManagerForEMS")
public class PortalInquiryManService extends BaseService {
	private final PortalInquiryService portalInquiryService;
	private final PortalInquiryUIMapper portalInquiryUIMapper;
	private final UserInfoService userInfoService;
	private final FileService fileService;

	public static final String PENDING = "PENDING";
	public static final String RESPONDED = "RESPONDED";


	public PortalInquiryManService(PortalInquiryService portalInquiryService,
								   PortalInquiryUIMapper portalInquiryUIMapper,
								   UserInfoService userInfoService,
								   FileService fileService){
		this.portalInquiryService = portalInquiryService;
		this.portalInquiryUIMapper = portalInquiryUIMapper;
		this.userInfoService = userInfoService;
		this.fileService = fileService;
	}

	public Page<PortalInquiryUI> selectList(Pageable pageable, PortalInquirySearch portalInquirySearch) {
		Page<Inquiry> inquiries = portalInquiryService.findAll(pageable, portalInquirySearch);
		return inquiries.map(inquiry -> {
			PortalInquiryUI ui = portalInquiryUIMapper.toVo(inquiry);
			setOrgName(ui, inquiry);
			// 문의자 정보 마스킹처리 _ 이름, 이메일, 로그인id, 핸드폰번호
			if (ui.getInquirer() != null) {
				maskPortalInquiryUI(ui);
			}
			return setInquiryAttachmentStatus(ui);
		});
	}

	private void setOrgName(PortalInquiryUI ui, Inquiry inquiry) {
		if (inquiry.getInquirer() == null) {
			ui.setOrgName("");
			return;
		}
		PortalUser inquirer = inquiry.getInquirer();
		boolean isCorpUser = inquirer.getRoleCode() == PortalUserEnums.RoleCode.ROLE_CORP_USER
				|| inquirer.getRoleCode() == PortalUserEnums.RoleCode.ROLE_CORP_MANAGER;

		if (isCorpUser && inquirer.getPortalOrg() != null) {
			ui.setOrgName(inquirer.getPortalOrg().getOrgName());
		} else {
			ui.setOrgName("");
		}
	}

	private PortalInquiryUI setInquiryAttachmentStatus(PortalInquiryUI ui) {
		String fileId = ui.getAttachFile();
		FileInfo fileInfo = null;

		if(StringUtils.isNotBlank(fileId)){
			fileInfo = fileService.findById(fileId);
		}

		boolean hasAttachment = false;

		if(fileInfo != null && fileInfo.getFileDetails() != null) {
			hasAttachment = !fileInfo.getFileDetails().isEmpty();
		}

		ui.setHasAttachment(hasAttachment);
		return ui;
	}

	public PortalInquiryUI selectDetail(String id) {
		Inquiry inquiry = portalInquiryService.getById(id);
		PortalInquiryUI portalInquiryUI =  portalInquiryUIMapper.toVo(inquiry);

		// 문의자 정보 마스킹처리 _ 이름, 이메일, 로그인id, 핸드폰번호
		if (portalInquiryUI.getInquirer() != null) {
			maskPortalInquiryUI(portalInquiryUI);
		}

		if (StringUtils.isNotBlank(inquiry.getAttachFile())) {
			FileInfo fileInfo = fileService.findById(inquiry.getAttachFile());
			if (fileInfo != null && fileInfo.getFileDetails() != null && !fileInfo.getFileDetails().isEmpty()) {
				portalInquiryUI.setFileInfo(fileInfo);
			}
		}

		return portalInquiryUI;
	}

	private void maskPortalInquiryUI(PortalInquiryUI ui) {
		if (StringUtils.isNotBlank(ui.getInquirer().getUserName())) {
			ui.getInquirer().setUserName(MaskingUtils.maskName(ui.getInquirer().getUserName()));
		}
		if (StringUtils.isNotBlank(ui.getInquirer().getMobileNumber())) {
			ui.getInquirer().setMobileNumber(MaskingUtils.maskPhoneNumber(ui.getInquirer().getMobileNumber()));
		}
		if (StringUtils.isNotBlank(ui.getInquirer().getLoginId())) {
			ui.getInquirer().setLoginId(MaskingUtils.maskEmailId(ui.getInquirer().getLoginId()));
		}
		if (StringUtils.isNotBlank(ui.getInquirer().getEmailAddr())) {
			ui.getInquirer().setEmailAddr(MaskingUtils.maskEmailId(ui.getInquirer().getEmailAddr()));
		}
	}

	public void insertAndUpdate(PortalInquiryUI portalInquiryUI, String userId) {
		UserInfo userinfo = userInfoService.getById(userId);

		Inquiry inquiry = portalInquiryService.getById(portalInquiryUI.getId());
		// 답변 대기중 상태일 경우만 답변완료로 상태 변경
		if(inquiry.getInquiryStatus().equals(PENDING)) {
			inquiry.setInquiryStatus(RESPONDED);
		}

		inquiry.setResponseDetail(StringEscapeUtils.unescapeHtml(portalInquiryUI.getResponseDetail()));
		inquiry.setResponder(userinfo);
		inquiry.setResponseDate(LocalDateTime.now());

		portalInquiryService.save(inquiry);
	}

}
