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

import com.eactive.apim.portal.apprequest.entity.QAppRequest;
import com.eactive.apim.portal.portalorg.entity.PortalOrg;
import com.eactive.apim.portal.portalorg.entity.PortalOrgEnums;
import com.eactive.apim.portal.portalorg.entity.QPortalOrg;
import com.eactive.eai.rms.data.jpa.AbstractEMSDataSerivce;
import com.querydsl.core.BooleanBuilder;
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.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

@Service
@Transactional(transactionManager = "transactionManagerForEMS")
public class PortalOrgService extends AbstractEMSDataSerivce<PortalOrg, String, PortalOrgRepository> {

	public Page<PortalOrg> findAll(Pageable pageable, PortalOrgUISearch portalOrgUISearch) {
		QPortalOrg qPortalOrg = QPortalOrg.portalOrg;

		BooleanBuilder predicate = new BooleanBuilder();

		// 기본 list 조회시엔 REMOVED 상태 아닌 데이터만 조회
		if (StringUtils.isNotBlank(portalOrgUISearch.getSearchOrgStatus())){
			predicate.and(qPortalOrg.orgStatus.eq(PortalOrgEnums.OrgStatus.valueOf(portalOrgUISearch.getSearchOrgStatus())));
		} else if (!portalOrgUISearch.isIncludeRemoved()) {
			predicate.and(qPortalOrg.orgStatus.ne(PortalOrgEnums.OrgStatus.REMOVED));
		}

		if (StringUtils.isNotBlank(portalOrgUISearch.getSearchOrgName())) {
			predicate.and(qPortalOrg.orgName.containsIgnoreCase(portalOrgUISearch.getSearchOrgName()));
		}
		
		if (StringUtils.isNotBlank(portalOrgUISearch.getSearchApprovalStatus())) {
			predicate.and(qPortalOrg.approvalStatus.eq(PortalOrgEnums.ApprovalStatus.valueOf(portalOrgUISearch.getSearchApprovalStatus())));
		}

		if (StringUtils.isNotBlank(portalOrgUISearch.getSearchOrgCompRegNo())) {
			predicate.and(qPortalOrg.compRegNo.containsIgnoreCase(portalOrgUISearch.getSearchOrgCompRegNo()));
		}

		return repository.findAll(predicate, pageable);
	}

	public List<PortalOrg> findByOrgStatusAndApprovalStatus(String orgStatus, String approvalStatus){
		QPortalOrg qPortalOrg = QPortalOrg.portalOrg;
		BooleanBuilder predicate = new BooleanBuilder();

		if (StringUtils.isNotBlank(orgStatus)) {
			predicate.and(qPortalOrg.orgStatus.eq(PortalOrgEnums.OrgStatus.valueOf(orgStatus)));
		}

		if (StringUtils.isNotBlank(approvalStatus)) {
			predicate.and(qPortalOrg.approvalStatus.eq(PortalOrgEnums.ApprovalStatus.valueOf(approvalStatus)));
		}

        return StreamSupport.stream(
				repository.findAll(predicate).spliterator(), false)
				.collect(Collectors.toList());
	}

	public long countAppRequestByOrgId(String orgId) {
		return getJPAQueryFactory().selectFrom(QAppRequest.appRequest)
				.where(QAppRequest.appRequest.org.id.eq(orgId))
				.fetchCount();
	}
}