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

import com.google.common.collect.Maps;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.framework.dto.PageQuery;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.order.infra.database.rds.dao.pay.PayFactoryDAO;
import com.red.circle.order.infra.database.rds.entity.pay.PayFactory;
import com.red.circle.order.infra.database.rds.service.pay.PayFactoryService;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.text.StringUtils;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 支付渠道厂商 服务实现类.
 * </p>
 *
 * @author pengshigang
 * @since 2021-12-08
 */
@Service
@RequiredArgsConstructor
public class PayFactoryServiceImpl extends BaseServiceImpl<PayFactoryDAO, PayFactory> implements
    PayFactoryService {

  @Override
  public Map<String, PayFactory> mapByCodes(Set<String> codes) {
    if (CollectionUtils.isEmpty(codes)) {
      return Maps.newHashMap();
    }
    return Optional.ofNullable(query()
            .in(PayFactory::getFactoryCode, codes)
            .list())
        .map(sysPayChannels -> sysPayChannels.stream()
            .collect(Collectors.toMap(PayFactory::getFactoryCode, v -> v)))
        .orElseGet(Maps::newHashMap);
  }


  @Override
  public PageResult<PayFactory> pageSysPayChannel(PageQuery pageQuery, String factoryCode,
      String factoryName) {
    return query()
        .eq(StringUtils.isNotBlank(factoryCode), PayFactory::getFactoryCode,
            factoryCode)
        .eq(StringUtils.isNotBlank(factoryName), PayFactory::getFactoryName,
            factoryName)
        .orderByDesc(PayFactory::getCreateTime)
        .page(pageQuery);
  }

  @Override
  public List<PayFactory> listSysPayChannel() {
    return query().orderByDesc(PayFactory::getCreateTime).list();
  }

  @Override
  public void addSysPayChannel(PayFactory entity) {
    try {
      save(entity);
    } catch (DuplicateKeyException ignore) {
      ResponseAssert.failure(CommonErrorCode.INFORMATION_EXISTS);
    }
  }

  @Override
  public void updateSysPayChannel(PayFactory entity) {
    updateSelectiveById(entity);
  }
}
