package com.red.circle.order.infra.database.rds.service.pay.impl;

import com.red.circle.framework.mybatis.constant.PageConstant;
import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.order.infra.database.rds.dao.pay.PayFactoryConfigDAO;
import com.red.circle.order.infra.database.rds.entity.pay.PayFactoryConfig;
import com.red.circle.order.infra.database.rds.service.pay.PayFactoryConfigService;
import com.red.circle.tool.core.text.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 支付厂商运行配置.
 */
@Service
public class PayFactoryConfigServiceImpl extends
    BaseServiceImpl<PayFactoryConfigDAO, PayFactoryConfig> implements PayFactoryConfigService {

  @Override
  public PayFactoryConfig getByScope(String factoryCode, String env, String sysOrigin) {
    return getByScope(factoryCode, env, sysOrigin, null);
  }

  @Override
  public PayFactoryConfig getEnabledByScope(String factoryCode, String env, String sysOrigin) {
    PayFactoryConfig exact = getByScope(factoryCode, env, sysOrigin, Boolean.TRUE);
    if (exact != null) {
      return exact;
    }
    PayFactoryConfig envDefault = getByScope(factoryCode, env, "", Boolean.TRUE);
    if (envDefault != null) {
      return envDefault;
    }
    PayFactoryConfig originDefault = getByScope(factoryCode, "", sysOrigin, Boolean.TRUE);
    if (originDefault != null) {
      return originDefault;
    }
    return getByScope(factoryCode, "", "", Boolean.TRUE);
  }

  private PayFactoryConfig getByScope(String factoryCode, String env, String sysOrigin,
      Boolean enabled) {
    return query()
        .eq(PayFactoryConfig::getFactoryCode, normalize(factoryCode))
        .eq(PayFactoryConfig::getEnv, normalize(env))
        .eq(PayFactoryConfig::getSysOrigin, normalize(sysOrigin))
        .eq(enabled != null, PayFactoryConfig::getEnabled, enabled)
        .last(PageConstant.LIMIT_ONE)
        .getOne();
  }

  private String normalize(String value) {
    return StringUtils.isBlank(value) ? "" : value.trim();
  }
}
