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

import com.google.common.collect.Maps;
import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.framework.mybatis.constant.PageConstant;
import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.other.infra.database.rds.dao.dynamic.DynamicTagDAO;
import com.red.circle.other.infra.database.rds.entity.dynamic.DynamicTag;
import com.red.circle.other.infra.database.rds.service.dynamic.DynamicTagService;
import com.red.circle.other.inner.model.cmd.dynamic.PageDynamicTagQryCmd;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.tool.core.text.StringUtils;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 动态-朋友圈标签 服务实现类.
 * </p>
 *
 * @author pengshigang
 * @since 2022-04-11
 */
@Service
@RequiredArgsConstructor
public class DynamicTagServiceImpl extends BaseServiceImpl<DynamicTagDAO, DynamicTag> implements
    DynamicTagService {

  @Override
  public Map<Long, DynamicTag> mapByIds(Collection<Long> ids) {
    if (CollectionUtils.isEmpty(ids)) {
      return Maps.newHashMap();
    }
    return Optional.ofNullable(
            query().in(DynamicTag::getId, ids)
                .last(PageConstant.formatLimit(ids.size()))
                .list()
        ).map(tags -> tags.stream().collect(Collectors.toMap(DynamicTag::getId, v -> v)))
        .orElse(Maps.newHashMap());
  }

  @Override
  public List<DynamicTag> listTag(SysOriginPlatformEnum sysOrigin, String language) {
    return query()
        .eq(DynamicTag::getSysOrigin, sysOrigin.name())
        .eq(DynamicTag::getLanguageType, language)
        .eq(DynamicTag::getDel, Boolean.FALSE)
        .orderByDesc(DynamicTag::getSort, DynamicTag::getCreateTime)
        .list();

  }

  @Override
  public void addOrUpdate(DynamicTag dynamicTag) {

    if (Objects.isNull(dynamicTag.getId())) {

      dynamicTag.setCreateTime(TimestampUtils.now());
      save(dynamicTag);

    } else {

      updateSelectiveById(dynamicTag);
    }
  }


  @Override
  public PageResult<DynamicTag> pageData(PageDynamicTagQryCmd query) {

    return query()
        .eq(StringUtils.isNotBlank(query.getSysOrigin()), DynamicTag::getSysOrigin,
            query.getSysOrigin())
        .eq(StringUtils.isNotBlank(query.getLanguageType()), DynamicTag::getLanguageType,
            query.getLanguageType())
        .eq(Objects.nonNull(query.getDel()), DynamicTag::getDel, query.getDel())
        .orderByDesc(DynamicTag::getSort, DynamicTag::getCreateTime)
        .page(query.getPageQuery());

  }


}
