package com.seer.teach.mall.good.service.impl;

import cn.hutool.core.collection.CollUtil;
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.seer.teach.mall.entity.GoodsLogEntity;
import com.seer.teach.mall.good.service.IAdminGoodsLogService;
import com.seer.teach.mall.service.IGoodsLogService;
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.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Slf4j
@Service
public class AdminGoodsLogServiceImpl implements IAdminGoodsLogService {

    private final IGoodsLogService goodsLogService;

    private final UserInfoServiceApi userInfoServiceApi;

    @Override
    public IPage<GoodsLogEntity> queryPageList(Integer goodsId, Integer pageSize, Integer pageNo) {
        IPage<GoodsLogEntity> pageParams = new Page<>(pageNo, pageSize);
        log.info("分页查询商品[{}]日志列表，参数：{}", goodsId,pageParams);
        IPage<GoodsLogEntity> iPage = goodsLogService.page(pageParams, new LambdaQueryWrapper<GoodsLogEntity>()
                .eq(GoodsLogEntity::getGoodsId, goodsId)
                .orderByDesc(GoodsLogEntity::getId));
        log.info("分页查询商品日志列表数量：{}", iPage.getTotal());
        if(CollUtil.isEmpty(iPage.getRecords())){
            return new Page<>();
        }
        Set<Integer> userIds = iPage.getRecords().stream().map(GoodsLogEntity::getOperatorId).collect(Collectors.toSet());
        List<UserInfoDTO> users = userInfoServiceApi.getListByUserIds(userIds);
        if(CollUtil.isEmpty( users)){
            return iPage;
        }
        Map<Integer, UserInfoDTO> userInfoMap = users.stream().collect(Collectors.toMap(UserInfoDTO::getId, Function.identity(), (old, newOne) -> newOne));
        iPage.getRecords().forEach(goodsLogEntity -> {
            UserInfoDTO userInfoDTO = userInfoMap.get(goodsLogEntity.getOperatorId());
            if(Objects.nonNull(userInfoDTO)){
                goodsLogEntity.setOperatorName(getUserName(userInfoDTO));
            }
        });
        return iPage;
    }

    private String getUserName(UserInfoDTO userInfoDTO){
        if(StringUtils.hasText(userInfoDTO.getUserName())){
            return userInfoDTO.getUserName();
        }
        if(StringUtils.hasText(userInfoDTO.getNickName())){
            return userInfoDTO.getNickName();
        }
        if(StringUtils.hasText(userInfoDTO.getRealName())){
            return userInfoDTO.getRealName();
        }
        return userInfoDTO.getMobile();
    }
}
