package com.seer.teach.mall.order.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.ResultBean;
import com.seer.teach.common.utils.PageConverterUtils;
import com.seer.teach.mall.convert.AfterSaleLogConvert;
import com.seer.teach.mall.entity.TradeAfterSaleLogEntity;
import com.seer.teach.mall.request.AfterSaleLogPageReq;
import com.seer.teach.mall.response.AfterSaleLogResp;
import com.seer.teach.mall.service.ITradeAfterSaleLogService;
import com.seer.teach.user.api.UserInfoServiceApi;
import com.seer.teach.user.api.dto.UserInfoDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

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

@Slf4j
@Service
@RequiredArgsConstructor
public class AdminAfterSaleLogService {

    private final ITradeAfterSaleLogService tradeAfterSaleLogService;

    private final UserInfoServiceApi userInfoServiceApi;

    public PageListBean<AfterSaleLogResp> getPageList(AfterSaleLogPageReq reqVO){
        IPage<TradeAfterSaleLogEntity> pageResult = tradeAfterSaleLogService.pageList(reqVO);

        PageListBean<AfterSaleLogResp> result = PageConverterUtils.convertPageListBean(pageResult, AfterSaleLogConvert.INSTANCE::toRespList);

        // 获取操作人信息
        Set<Integer> operatorIds = result.getList().stream()
                .map(AfterSaleLogResp::getOperatorId)
                .filter(id -> id != null && id > 0)
                .collect(Collectors.toSet());

        if (!operatorIds.isEmpty()) {
            List<UserInfoDTO> userInfos = userInfoServiceApi.getListByUserIds(operatorIds);
            Map<Integer, String> userMap = userInfos.stream()
                    .collect(Collectors.toMap(UserInfoDTO::getId,
                            user -> StringUtils.hasText(user.getNickName()) ? user.getNickName() : user.getUserName(),
                            (oldValue, newValue) -> newValue));

            result.getList().forEach(log -> {
                if (log.getOperatorId() != null && log.getOperatorId() > 0) {
                    log.setOperatorName(userMap.getOrDefault(log.getOperatorId(), "未知用户"));
                }
            });
        }
        return result;
    }
}
