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

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seer.teach.common.PageListBean;
import com.seer.teach.mall.entity.BrowsingHistoryEntity;
import com.seer.teach.mall.entity.GoodsEntity;
import com.seer.teach.mall.mapper.GoodsMapper;
import com.seer.teach.mall.request.BrowsingHistoryPageReq;
import com.seer.teach.mall.request.BrowsingSaveReq;
import com.seer.teach.mall.response.BrowsingHistoryPageResp;
import com.seer.teach.mall.mapper.BrowsingHistoryMapper;
import com.seer.teach.mall.service.BrowsingHistoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Captain
 * @since 2025-06-18
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistoryEntity> implements BrowsingHistoryService {

    private final GoodsMapper goodsMapper;
    /**
     * 新增浏览足迹
     *
     * @param params
     * @return
     */
    @Override
    public void addBrowsingHistory(BrowsingSaveReq params) {
        //获取当前登录用户的ID
        Integer userId = StpUtil.getLoginIdAsInt();
        // 查询是否已有浏览记录
        BrowsingHistoryEntity result = getOne(new LambdaQueryWrapper<BrowsingHistoryEntity>()
                .eq(BrowsingHistoryEntity::getUserId, userId)
                .eq(BrowsingHistoryEntity::getGoodsId, params.getId())
        );
            if(result != null){
                //若已存在,则更新浏览时间
                result.setBrowsedTime(LocalDateTime.now());
                updateById(result);
            }
            else{
                //不存在,新增浏览足迹
                BrowsingHistoryEntity history = new BrowsingHistoryEntity();
                history.setUserId(userId);
                history.setGoodsId(params.getId());
                history.setBrowsedTime(LocalDateTime.now());
                save(history);
            }
    }

    /**
     * 删除浏览足迹
     * @param ids
     */
    @Override
    public void deleteBrowsingHistory(List<Integer> ids) {
        Integer userId = StpUtil.getLoginIdAsInt();
        LambdaQueryWrapper<BrowsingHistoryEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BrowsingHistoryEntity::getUserId,userId)
                .in(BrowsingHistoryEntity::getGoodsId,ids);
        remove(wrapper);
    }

    /**
     * 清空所有浏览足迹
     */
    @Override
    public void clearBrowsingHistory() {
        Integer userId = StpUtil.getLoginIdAsInt();
        LambdaQueryWrapper<BrowsingHistoryEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BrowsingHistoryEntity::getUserId,userId);
        remove(wrapper);
    }

    /**
     * 分页查询浏览足迹
     * @param params
     * @return
     */
    @Override
    public PageListBean<BrowsingHistoryPageResp> getBrowsingHistoryPage(BrowsingHistoryPageReq params) {
        Integer userId = StpUtil.getLoginIdAsInt();
        Page<BrowsingHistoryEntity> pageParams = new Page<>(params.getPage(), params.getLimits());
        LambdaQueryWrapper<BrowsingHistoryEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BrowsingHistoryEntity::getUserId,userId)
                .orderByDesc(BrowsingHistoryEntity::getBrowsedTime);
        Page<BrowsingHistoryEntity> historyPage = this.page(pageParams, wrapper);
        if (CollectionUtils.isEmpty(historyPage.getRecords())) {
            log.warn("用户[{}]没有浏览足迹", userId);
            return new PageListBean<>();
        }
        //获取商品Id
        List<Integer> goodsIdList = historyPage.getRecords().stream().map(BrowsingHistoryEntity::getGoodsId)
                .distinct().collect(Collectors.toList());
        LambdaQueryWrapper<GoodsEntity> goodsWrapper = new LambdaQueryWrapper<>();
        goodsWrapper.in(GoodsEntity::getId,goodsIdList);
        if (StringUtils.isNotBlank(params.getName())) {
            goodsWrapper.like(GoodsEntity::getName, params.getName());
        }
        List<GoodsEntity> goodsList = goodsMapper.selectList(goodsWrapper);
        Map<Integer, GoodsEntity> goodsMap = goodsList.stream()
                .collect(Collectors.toMap(GoodsEntity::getId, Function.identity()));
        //拼接返回值
        List<BrowsingHistoryPageResp> respList = new ArrayList<>();
        historyPage.getRecords().forEach(i->{
            GoodsEntity goods = goodsMap.get(i.getGoodsId());
            if(goods != null){
                BrowsingHistoryPageResp resp = new BrowsingHistoryPageResp();
                resp.setGoodsId(goods.getId());
                resp.setName(goods.getName());
                resp.setPrimaryPicUrl(goods.getPrimaryPicUrl());
                resp.setBrowsedTime(i.getBrowsedTime());
                resp.setPrice(goods.getPrice());
                respList.add(resp);
            }
        });
        PageListBean<BrowsingHistoryPageResp> pageListBean = new PageListBean<>();
        pageListBean.setList(respList);
        pageListBean.setPage(historyPage.getCurrent());
        pageListBean.setPageSize(historyPage.getSize());
        pageListBean.setTotal(historyPage.getTotal());
        pageListBean.setTotalPage(historyPage.getPages());
        log.info("用户[{}]浏览足迹分页查询完成，共返回 {} 条记录", userId, respList.size());
        return pageListBean;
    }


}
