package com.red.circle.console.app.service.app.props;

import com.red.circle.console.app.dto.clienobject.props.RoomThemeUserCustomizeCO;
import com.red.circle.console.app.dto.cmd.app.props.ApprovalContentDTO;
import com.red.circle.console.app.dto.cmd.app.props.ApprovalThemeCmd;
import com.red.circle.console.infra.database.rds.entity.admin.User;
import com.red.circle.console.infra.database.rds.service.admin.UserService;
import com.red.circle.external.inner.endpoint.message.OfficialNoticeClient;
import com.red.circle.external.inner.model.cmd.message.notice.official.NoticeExtTemplateTypeCmd;
import com.red.circle.external.inner.model.enums.message.OfficialNoticeTypeEnum;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.other.inner.endpoint.material.props.RoomThemeUserBackpackClient;
import com.red.circle.other.inner.endpoint.material.props.RoomThemeUserCustomizeClient;
import com.red.circle.other.inner.model.cmd.material.RoomThemeUserCustomizeApprovalCmd;
import com.red.circle.other.inner.model.cmd.material.RoomThemeUserCustomizeOpsPageQryCmd;
import com.red.circle.other.inner.model.dto.material.RoomThemeUserBackpackDTO;
import com.red.circle.other.inner.model.dto.material.RoomThemeUserCustomizeDTO;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.tool.core.num.ArithmeticUtils;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.other.inner.endpoint.user.user.UserProfileClient;
import com.red.circle.wallet.inner.endpoint.wallet.WalletGoldClient;
import com.red.circle.wallet.inner.model.cmd.GoldReceiptCmd;
import com.red.circle.wallet.inner.model.enums.GoldOrigin;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 用户房间主题.
 *
 * @author pengliang on 2023/12/4
 */
@Service
@RequiredArgsConstructor
public class RoomThemeUserCustomizeServiceImpl implements RoomThemeUserCustomizeService {

  private final UserService userService;
  private final WalletGoldClient walletGoldClient;
  private final UserProfileClient userProfileClient;
  private final OfficialNoticeClient officialNoticeClient;
  private final RoomThemeUserBackpackClient roomThemeUserBackpackClient;
  private final RoomThemeUserCustomizeClient roomThemeUserCustomizeClient;

  @Override
  public PageResult<RoomThemeUserCustomizeCO> pageOps(
      RoomThemeUserCustomizeOpsPageQryCmd pageQryCmd) {

    PageResult<RoomThemeUserCustomizeDTO> pageResult = roomThemeUserCustomizeClient.pageOps(
        pageQryCmd).getBody();

    if (pageResult.checkRecordsEmpty()) {
      return pageResult.emptyRecords();
    }

    Map<Long, UserProfileDTO> userBaseInfoMap = userProfileClient.mapByUserIds(pageResult
            .getRecords().stream().map(RoomThemeUserCustomizeDTO::getUserId)
            .collect(Collectors.toSet()))
        .getBody();

    Map<Long, User> userMap = userService.mapBackUser(
        pageResult.getRecords().stream().map(RoomThemeUserCustomizeDTO::getUpdateUser)
            .filter(Objects::nonNull).collect(Collectors.toSet()));

    return pageResult.convert(roomUserTheme -> {
      RoomThemeUserCustomizeCO customizeCO = new RoomThemeUserCustomizeCO();
      customizeCO.setCustomize(roomUserTheme);
      customizeCO.setUserProfile(userBaseInfoMap.get(roomUserTheme.getUserId()));
      if (Objects.nonNull(roomUserTheme.getUpdateUser())) {
        User user = userMap.get(roomUserTheme.getUpdateUser());
        customizeCO.setOptUserNickname(Objects.nonNull(user) ? user.getNickname() : null);
      }
      return customizeCO;
    });
  }

  @Override
  public void themeApprove(ApprovalThemeCmd cmd) {

    if (CollectionUtils.isEmpty(cmd.getWaitApprovalUser())) {
      return;
    }

    roomThemeUserCustomizeClient.updateApprovalStatus(
        new RoomThemeUserCustomizeApprovalCmd()
            .setApprovalUserId(cmd.getApprovalUserId())
            .setApprovalStatus(cmd.getApprovalStatus())
            .setContentIds(cmd.getWaitApprovalUserContentIds())
    );

    Map<Long, UserProfileDTO> longUserProfileDTOMap = userProfileClient.mapByUserIds(
        cmd.getWaitApprovalUserIdsSet()).getBody();
    if (CollectionUtils.isEmpty(longUserProfileDTOMap)) {
      return;
    }

    // 退款
    if (cmd.approvalNotPass()) {
      for (ApprovalContentDTO content : cmd.getWaitApprovalUser()) {

        UserProfileDTO userProfile = longUserProfileDTOMap.get(content.getUserId());
        if (Objects.nonNull(userProfile)) {
          walletGoldClient.changeBalance(GoldReceiptCmd.builder()
              .opsIncome()
              .userId(content.getUserId())
              .eventId(content.getContentId())
              .sysOrigin(userProfile.getOriginSys())
              .origin(GoldOrigin.CUSTOM_THEME)
              .amount(ArithmeticUtils.toBigDecimal(content.getContent()))
              .build());
        }
      }
      // 推送通知
      /*officialNoticeClient.send(NoticeExtTemplateTypeCmd.builder()
          .toAccounts(cmd.getWaitApprovalUserIds())
          .noticeType(OfficialNoticeTypeEnum.ROOM_THEME_NOT_PASS)
          .build()
      );*/
      return;
    }

    for (ApprovalContentDTO approvalUserParam : cmd.getWaitApprovalUser()) {
      // 插入个人主题背包
      roomThemeUserBackpackClient.save(new RoomThemeUserBackpackDTO()
          .setThemeId(approvalUserParam.getContentId())
          .setUserId(approvalUserParam.getUserId())
          .setThemeType(1)
          .setUseTheme(Boolean.FALSE)
          .setExpireTime(TimestampUtils.nowPlusDays(30).getTime())
      );
    }
    // 推送通知
    /*officialNoticeClient.send(NoticeExtTemplateTypeCmd.builder()
        .toAccounts(cmd.getWaitApprovalUserIds())
        .noticeType(OfficialNoticeTypeEnum.ROOM_THEME_PASS)
        .build()
    );*/

  }

}
