package com.eactive.eai.rms.data.entity.onl.stdmessage;

import com.eactive.eai.data.entity.onl.adapter.AdapterGroup;
import com.eactive.eai.data.entity.onl.message.QEAIMessageEntity;
import com.eactive.eai.data.entity.onl.stdmessage.QStandardMessageInfo;
import com.eactive.eai.data.entity.onl.stdmessage.StandardMessageInfo;
import com.eactive.eai.data.jpa.AbstractDataService;
import com.eactive.eai.rms.data.entity.onl.bzwkdstcd.UserBusinessService;
import com.querydsl.core.Tuple;
import com.querydsl.jpa.impl.JPAQuery;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class StandardMessageInfoService
		extends AbstractDataService<StandardMessageInfo, String, StandardMessageInfoEMSRepository> {

	private UserBusinessService userBusinessService;

	@Autowired
	public StandardMessageInfoService(UserBusinessService userBusinessService) {
		this.userBusinessService = userBusinessService;
	}
	
	public Page<StandardMessageInfo> findAll(Pageable pageable, String searchBzwkSvcKeyName, String searchEaiSvcCode,
			String searchEaiSendRecv, String searchEaiDirection) {

		QStandardMessageInfo qStandardMessageInfo = QStandardMessageInfo.standardMessageInfo;
		QEAIMessageEntity qeaiMessageEntity = QEAIMessageEntity.eAIMessageEntity;

		qStandardMessageInfo.bzwksvckeyname.containsIgnoreCase(searchBzwkSvcKeyName);

		List<String> userBusiness = userBusinessService.getCurrentUserBusinessCodes();

		JPAQuery<StandardMessageInfo> query = getJPAQueryFactory()
				.select(qStandardMessageInfo)
				.from(qStandardMessageInfo);

		if (StringUtils.isNotBlank(searchBzwkSvcKeyName)) {
			query.where(qStandardMessageInfo.bzwksvckeyname.containsIgnoreCase(searchBzwkSvcKeyName));
		}
		if (StringUtils.isNotBlank(searchEaiSvcCode)) {
			query.where(qStandardMessageInfo.eaisvcname.containsIgnoreCase(searchEaiSvcCode));
		}
		if (StringUtils.isNotBlank(searchEaiSendRecv)) {
			query.where(qStandardMessageInfo.eaisendrecv.eq(searchEaiSendRecv));
		}
		if (StringUtils.isNotBlank(searchEaiDirection)) {
			query.where(qStandardMessageInfo.eaidirection.eq(searchEaiDirection));
		}

		JPAQuery<String> userEaisvcnames = getJPAQueryFactory()
				.select(qeaiMessageEntity.eaisvcname)
				.from(qeaiMessageEntity)
				.where(qeaiMessageEntity.eaibzwkdstcd.in(userBusiness));

		JPAQuery<String> notInEaisvcnames = getJPAQueryFactory()
				.select(qeaiMessageEntity.eaisvcname)
				.from(qeaiMessageEntity);

		// 사용자 에게 권한이 있는 EaiSvcName 과 정의 되어 있지 않은 EaiSvcName를 포함 하여 조회
		query
				.where(qStandardMessageInfo.eaisvcname
						.in(userEaisvcnames)
						.or(qStandardMessageInfo.eaisvcname.notIn(notInEaisvcnames)));

		long totalCount = query.select(qStandardMessageInfo.count()).fetchOne();

		query.select(qStandardMessageInfo).orderBy(qStandardMessageInfo.bzwksvckeyname.asc());

		List<StandardMessageInfo> standardMessageInfos = null;

		if (pageable.isPaged()) {
			standardMessageInfos = query.limit(pageable.getPageSize()).offset(pageable.getOffset()).fetch();
		} else {
			standardMessageInfos = query.fetch();
		}

		return new PageImpl<>(standardMessageInfos, pageable, totalCount);
	}

   public Iterable<StandardMessageInfo> findByEaiSvcCode(String searchEaiSvcCode) {
      return repository.findAll(QStandardMessageInfo.standardMessageInfo.eaisvcname.containsIgnoreCase(searchEaiSvcCode));
   }
	
	public List<Map<String, Object>> selectApiListCombo() {
		QEAIMessageEntity qEaiMessageEntity = QEAIMessageEntity.eAIMessageEntity;
		QStandardMessageInfo qStandardMessageInfo = QStandardMessageInfo.standardMessageInfo;
		
		List<Tuple> result = getJPAQueryFactory()
				.select(qStandardMessageInfo.bzwksvckeyname, 
						qEaiMessageEntity.eaisvcdesc)
				.from(qStandardMessageInfo)
				.join(qEaiMessageEntity)
				.on(qStandardMessageInfo.eaisvcname.eq(qEaiMessageEntity.eaisvcname))
				.orderBy(qStandardMessageInfo.bzwksvckeyname.asc())
				.fetch();
		
		return result.stream().map(tuple -> {
			Map<String, Object> map = new HashMap<>();
			map.put("APIID", tuple.get(qStandardMessageInfo.bzwksvckeyname));
			map.put("APINAME", tuple.get(qEaiMessageEntity.eaisvcdesc));
			return map;
		}).collect(Collectors.toList());
	}
	
	public List<StandardMessageInfo> findByBzwksvckeynameStartingWith(String adapterName) {
        QStandardMessageInfo qStandardMessageInfo = QStandardMessageInfo.standardMessageInfo;

        return getJPAQueryFactory()
                .selectFrom(qStandardMessageInfo)
                .where(qStandardMessageInfo.bzwksvckeyname.startsWith(adapterName))
                .fetch();
    }
	
	public StandardMessageInfo saveAndFlush(StandardMessageInfo stdMsgInfo) {
        return repository.saveAndFlush(stdMsgInfo);
    }

}
