package com.eactive.eai.rms.data.entity.onl.apim.portalinquiry;

import java.util.List;

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 com.eactive.apim.portal.qna.entity.Inquiry;
import com.eactive.apim.portal.qna.entity.QInquiry;
import com.eactive.eai.rms.data.jpa.AbstractEMSDataSerivce;
import com.querydsl.core.BooleanBuilder;

@Service
@Transactional(transactionManager = "transactionManagerForEMS")
public class PortalInquiryService extends AbstractEMSDataSerivce<Inquiry, String, PortalInquiryRepository> {

	// AbstractEMSDataSerivce의 repository 필드가 BaseRepository<T,I>로 고정되어
	// 커스텀 메서드를 호출할 수 없으므로 별도 필드로 직접 주입
	@Autowired
	private PortalInquiryRepository portalInquiryRepository;

	public Page<Inquiry> findAll(Pageable pageable, PortalInquirySearch portalInquirySearch) {
		QInquiry qInquiry = QInquiry.inquiry;

		BooleanBuilder predicate = new BooleanBuilder();

		if (StringUtils.isNotBlank(portalInquirySearch.getSearchInquiryStatus())) {
			predicate.and(qInquiry.inquiryStatus.eq(portalInquirySearch.getSearchInquiryStatus()));
		}

		if (StringUtils.isNotBlank(portalInquirySearch.getSearchSubjectDetail())) {
			predicate.and(qInquiry.inquirySubject.containsIgnoreCase(portalInquirySearch.getSearchSubjectDetail())
					.or(qInquiry.inquiryDetail.containsIgnoreCase(portalInquirySearch.getSearchSubjectDetail())));
		}

		if (StringUtils.isNotBlank(portalInquirySearch.getSearchInquiryUserName())) {
			predicate.and(qInquiry.inquirer.userName.containsIgnoreCase(portalInquirySearch.getSearchInquiryUserName()));
		}

		if (StringUtils.isNotBlank(portalInquirySearch.getSearchOrgId())) {
			predicate.and(qInquiry.inquirer.portalOrg.id.eq(portalInquirySearch.getSearchOrgId()));
		}

		return repository.findAll(predicate, pageable);
	}

	public void deleteByIds(List<String> ids) {
		repository.deleteAllById(ids);
	}

	public long countByInquirerId(String userId) {
		return getJPAQueryFactory().selectFrom(QInquiry.inquiry)
				.where(QInquiry.inquiry.inquirer.id.eq(userId))
				.fetchCount();
	}

	public void deleteByInquirerId(String userId) {
		List<Inquiry> inquiries = getJPAQueryFactory().selectFrom(QInquiry.inquiry)
				.where(QInquiry.inquiry.inquirer.id.eq(userId))
				.fetch();
		if (!inquiries.isEmpty()) {
			repository.deleteAll(inquiries);
		}
	}

	public List<Inquiry> findByInquiryStatus(String inquiryStatus) {
		return portalInquiryRepository.findByInquiryStatus(inquiryStatus);
	}
}