package com.red.circle.other.infra.database.rds.service.family.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.other.infra.database.rds.dao.family.FamilyCreateRulesDAO;
import com.red.circle.other.infra.database.rds.entity.family.FamilyCreateRules;
import com.red.circle.other.infra.database.rds.service.family.FamilyCreateRulesService;
import com.red.circle.other.inner.model.cmd.famliy.FamilyCreateRuleQryCmd;
import java.math.BigDecimal;
import java.util.Objects;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 家族创建要求(满足任意一个，那么用户就可以创建家族) 服务实现类.
 * </p>
 *
 * @author pengshigang
 * @since 2021-07-21
 */
@Service
public class FamilyCreateRulesServiceImpl extends
    BaseServiceImpl<FamilyCreateRulesDAO, FamilyCreateRules> implements FamilyCreateRulesService {

  @Override
  public FamilyCreateRules getFamilyCreateRules(String sysOrigin) {
    return query().eq(FamilyCreateRules::getSysOrigin, sysOrigin).getOne();
  }

  @Override
  public void saveFamilyCreateRules(FamilyCreateRules param) {

    checkParam(param);

    FamilyCreateRules rule = getFamilyCreateRules(param.getSysOrigin());
    ResponseAssert.isFalse(CommonErrorCode.NOT_FOUND_RECORD_INFO,
        Objects.nonNull(rule) && !Objects.equals(rule.getId(), param.getId()));

    if (Objects.nonNull(param.getId())) {
      updateSelectiveById(param);
      return;
    }
    save(param);
  }

  private void checkParam(FamilyCreateRules param) {
    ResponseAssert.isFalse(CommonErrorCode.DATA_ERROR,
        BigDecimal.ZERO.compareTo(param.getPayCandy()) >= 0 &&
            param.getUserWealthLevel() <= 0);
  }

  @Override
  public PageResult<FamilyCreateRules> pageData(FamilyCreateRuleQryCmd queryWhere) {
    return query()
        .eq(Objects.nonNull(queryWhere.getId()), FamilyCreateRules::getId, queryWhere.getId())
        .eq(StringUtils.isNotEmpty(queryWhere.getSysOrigin()), FamilyCreateRules::getSysOrigin,
            queryWhere.getSysOrigin())
        .orderByAsc(FamilyCreateRules::getCreateTime)
        .page(queryWhere.getPageQuery());
  }
}
