package com.red.circle.other.app.command.propcoupon.query;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.other.app.convertor.PropCouponConvertor;
import com.red.circle.other.app.dto.clientobject.PropCouponCO;
import com.red.circle.other.app.dto.clientobject.PropCouponRecordCO;
import com.red.circle.other.app.dto.cmd.PropCouponQueryCmd;
import com.red.circle.other.infra.database.rds.dao.props.PropCouponUseRecordDAO;
import com.red.circle.other.infra.database.rds.entity.props.PropCouponUseRecordDO;
import com.red.circle.other.inner.endpoint.user.user.UserProfileClient;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 查询道具券使用记录执行器
 *
 * @author system
 * @date 2025-11-05
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class PropCouponRecordQryExe {

    private final PropCouponUseRecordDAO propCouponUseRecordDAO;
    private final UserProfileClient userProfileClient;

    /**
     * 执行查询使用记录
     */
    public PageResult<PropCouponRecordCO> execute(PropCouponQueryCmd cmd) {
        // 1. 获取当前用户ID
        Long userId = cmd.requiredReqUserId();

        // 2. 构建查询条件
        LambdaQueryWrapper<PropCouponUseRecordDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PropCouponUseRecordDO::getUserId, userId);

        // 如果指定了券类型，添加过滤条件
        if (cmd.getCouponType() != null) {
            wrapper.eq(PropCouponUseRecordDO::getCouponType, cmd.getCouponType());
        }

        // 按创建时间倒序
        wrapper.orderByDesc(PropCouponUseRecordDO::getCreateTime);

        // 3. 分页查询
        Page<PropCouponUseRecordDO> page = new Page<>(cmd.getCurrent(), cmd.getSize());
        IPage<PropCouponUseRecordDO> recordPage = propCouponUseRecordDAO.selectPage(page, wrapper);

        // 4. 获取接收人信息（用于赠送记录）
        Set<Long> receiverIds = recordPage.getRecords().stream()
                .filter(record -> record.getReceiverId() != null)
                .map(PropCouponUseRecordDO::getReceiverId)
                .collect(Collectors.toSet());

        Map<Long, UserProfileDTO> receiverMap = Map.of();
        if (!receiverIds.isEmpty()) {
            receiverMap = userProfileClient.mapByUserIds(receiverIds).getBody();
        }

        // 5. 转换为CO对象
        Map<Long, UserProfileDTO> finalReceiverMap = receiverMap;
        List<PropCouponRecordCO> recordCOList = recordPage.getRecords().stream()
                .map(record -> {
                    PropCouponRecordCO co = PropCouponConvertor.toRecordClientObject(record);
                    // 如果是赠送记录，填充接收人昵称
                    if (record.getReceiverId() != null && finalReceiverMap.containsKey(record.getReceiverId())) {
                        UserProfileDTO receiver = finalReceiverMap.get(record.getReceiverId());
                        co.setReceiverNickname(receiver.getUserNickname());
                        co.setReceiverAccount(receiver.getAccount());
                    }
                    return co;
                })
                .collect(Collectors.toList());

        // 6. 返回分页结果
        PageResult<PropCouponRecordCO> pageResult = new PageResult<>();
        pageResult.setTotal(recordPage.getTotal());
        pageResult.setRecords(recordCOList);
        pageResult.setCurrent(cmd.getCurrent());
        pageResult.setSize(cmd.getSize());
        return pageResult;
    }
}
