package com.red.circle.other.app.inner.service.material.props.impl;

import com.google.common.collect.Maps;
import com.red.circle.framework.mybatis.constant.PageConstant;
import com.red.circle.other.app.inner.convertor.material.PropsRedPacketSkinConvertor;
import com.red.circle.other.app.inner.service.material.props.PropsRedPacketSkinClientService;
import com.red.circle.other.infra.database.rds.entity.props.PropsRedPacketSkin;
import com.red.circle.other.infra.database.rds.service.props.PropsRedPacketSkinService;
import com.red.circle.other.inner.model.cmd.material.PropsRedPacketSkinCmd;
import com.red.circle.other.inner.model.dto.material.PropsRedPacketSkinDTO;
import com.red.circle.tool.core.date.TimestampUtils;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 红包皮肤图片
 *
 * @author zongpubin on 2024/1/29
 */
@Service
@RequiredArgsConstructor
public class PropsRedPacketSkinClientServiceImpl implements PropsRedPacketSkinClientService {

  private final PropsRedPacketSkinService propsRedPacketSkinService;
  private final PropsRedPacketSkinConvertor propsRedPacketSkinConvertor;

  @Override
  public PropsRedPacketSkinDTO getPropsRedPacketSkin(Long id) {
    return propsRedPacketSkinConvertor.toPropsRedPacketSkinDTO(
        propsRedPacketSkinService.getById(id));
  }

  @Override
  public void saveRedPacketSkin(PropsRedPacketSkinCmd skinParam) {

    PropsRedPacketSkin skin = propsRedPacketSkinService.getById(skinParam.getId());
    if (Objects.isNull(skin)) {
      propsRedPacketSkinService.save(propsRedPacketSkinConvertor.toPropsRedPacketSkin(skinParam));
      return;
    }

    propsRedPacketSkinService.update()
        .set(PropsRedPacketSkin::getImOpenedUrl, skin.getImOpenedUrl())
        .set(PropsRedPacketSkin::getImNotOpenedUrl, skin.getImNotOpenedUrl())
        .set(PropsRedPacketSkin::getImSendCoverUrl, skin.getImSendCoverUrl())
        .set(PropsRedPacketSkin::getRoomOpenedUrl, skin.getRoomOpenedUrl())
        .set(PropsRedPacketSkin::getRoomNotOpenedUrl, skin.getRoomNotOpenedUrl())
        .set(PropsRedPacketSkin::getRoomSendCoverUrl, skin.getRoomSendCoverUrl())
        .set(PropsRedPacketSkin::getUpdateTime, TimestampUtils.now())
        .set(PropsRedPacketSkin::getUpdateUser, skin.getUpdateUser())
        .eq(PropsRedPacketSkin::getId, skin.getId())
        .last(PageConstant.LIMIT_ONE)
        .execute();

  }

  @Override
  public Map<Long, PropsRedPacketSkinDTO> mapRedPacketSkinByIds(Set<Long> ids) {
    return Optional.ofNullable(propsRedPacketSkinService.mapByIds(ids))
        .map(packetSkins -> packetSkins.stream()
            .map(propsRedPacketSkinConvertor::toPropsRedPacketSkinDTO)
            .collect(Collectors.toMap(PropsRedPacketSkinDTO::getId, v -> v)))
        .orElse(Maps.newHashMap());
  }
}
