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

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.mall.convert.GoodsCollectConvert;
import com.seer.teach.mall.entity.GoodsCollectEntity;
import com.seer.teach.mall.entity.GoodsEntity;
import com.seer.teach.mall.request.GoodsCollectPageReq;
import com.seer.teach.mall.request.GoodsCollectReq;
import com.seer.teach.mall.response.GoodsCollectResp;
import com.seer.teach.mall.mapper.CollectMapper;
import com.seer.teach.mall.app.good.service.IAppCollectService;
import com.seer.teach.mall.app.good.service.IAppGoodsService;
import com.seer.teach.mall.service.IGoodsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品收藏服务实现类
 * </p>
 *
 * @author Sir-G
 * @since 2025-06-10
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class AppCollectServiceImpl extends ServiceImpl<CollectMapper, GoodsCollectEntity> implements IAppCollectService {

    private final IGoodsService goodsService;


    /**
     * 收藏商品
     *
     * @param params
     * @return
     */
    @Override
    public void collectGoods(GoodsCollectReq params) {
        //获取当前登录用户的ID
        Integer userId = StpUtil.getLoginIdAsInt();
        //判断商品是否已经收藏过
        GoodsCollectEntity one = getOne(new LambdaQueryWrapper<GoodsCollectEntity>()
                .eq(GoodsCollectEntity::getUserId, userId)
                .eq(GoodsCollectEntity::getGoodsId, params.getId())
                .eq(GoodsCollectEntity::getIsCollected, 1));
        AssertUtils.isNull(one, ResultCodeEnum.GOOD_ALREADY_COLLECTED);
        //首次收藏,添加收藏记录
        GoodsCollectEntity collect = new GoodsCollectEntity();
        collect.setUserId(userId);
        collect.setGoodsId(params.getId());
        collect.setIsCollected(1);
        collect.setCollectedTime(LocalDateTime.now());
        save(collect);
        //增加收藏数
        goodsService.increaseCollectCount(params.getId());
    }

    /**
     * 收藏商品分页查询
     *
     * @param params
     * @return
     */
    @Override
    public PageListBean<GoodsCollectResp> getGoodsCollectPage(GoodsCollectPageReq params) {
        // 获取登录用户的ID
        Integer userId = StpUtil.getLoginIdAsInt();
        // 查询收藏记录分页
        Page<GoodsCollectEntity> page = new Page<>(params.getPage(), params.getLimits());
        LambdaQueryWrapper<GoodsCollectEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GoodsCollectEntity::getUserId, userId)
                .eq(GoodsCollectEntity::getIsCollected, 1)
                .orderByDesc(GoodsCollectEntity::getCollectedTime);

        Page<GoodsCollectEntity> collectPage = this.page(page, wrapper);
        List<GoodsCollectEntity> collectList = collectPage.getRecords();
        if (CollectionUtils.isEmpty(collectList)) {
            return new PageListBean<>();
        }
        // 提取商品ID
        List<Integer> goodsIdList = collectList.stream()
                .map(GoodsCollectEntity::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 = goodsService.list(goodsWrapper);

        List<GoodsCollectResp> respList = new ArrayList<>();
        Map<Integer, GoodsEntity> goodsMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(goodsList)) {
            goodsMap.putAll(goodsList.stream()
                    .collect(Collectors.toMap(GoodsEntity::getId, Function.identity())));
        }
        // 组装响应列表
        collectList.forEach(collect -> {
            GoodsEntity goods = goodsMap.get(collect.getGoodsId());
            if (goods != null) {
                GoodsCollectResp resp = new GoodsCollectResp();
                resp.setId(collect.getId());
                resp.setGoodsId(goods.getId());
                resp.setName(goods.getName());
                resp.setPrimaryPicUrl(goods.getPrimaryPicUrl());
                resp.setCollectedTime(collect.getCollectedTime());
                resp.setPrice(goods.getPrice());
                respList.add(resp);
            }
        });
        // 返回分页结果
        PageListBean<GoodsCollectResp> result = new PageListBean<>();
        result.setList(respList);
        result.setPage(collectPage.getCurrent());
        result.setPageSize(collectPage.getSize());
        result.setTotal(collectPage.getTotal());
        result.setTotalPage(collectPage.getPages());
        log.info("用户[{}]成功返回收藏商品列表，共{}条记录", userId, respList.size());
        return result;
    }


    /**
     * 取消收藏商品
     *
     * @param goodIds
     * @return
     */
    @Override
    public boolean cancelCollect(List<Integer> goodIds) {
        // 获取当前登录用户的ID
        Integer userId = StpUtil.getLoginIdAsInt();
        List<GoodsCollectEntity> goodsCollects = super.list(
                new LambdaQueryWrapper<GoodsCollectEntity>()
                        .in(GoodsCollectEntity::getGoodsId, goodIds)
                        .eq(GoodsCollectEntity::getUserId, userId)
        );
        if (CollectionUtils.isEmpty(goodsCollects)) {
            log.info("用户[{}]取消收藏商品[{}]失败，未找到收藏记录", userId, goodIds.size());
            return false;
        }
        // 删除收藏记录
        boolean update = removeBatchByIds(goodsCollects);
        // 同步更新商品收藏量
        goodsCollects.forEach(collect -> {
            goodsService.decreaseCollectCount(collect.getGoodsId());
        });
        log.info("取消收藏商品结果:{}", update);
        return update;
    }

    @Override
    public GoodsCollectResp getGoodsCollect(int userId, GoodsCollectReq params) {
        GoodsCollectEntity collectEntity = super.getOne(new LambdaQueryWrapper<GoodsCollectEntity>().eq(GoodsCollectEntity::getUserId, userId).eq(GoodsCollectEntity::getGoodsId, params.getId()));
        if(Objects.isNull(collectEntity)){
            // 防止前端错误，返回一个空对象
            return new GoodsCollectResp();
        }
        return GoodsCollectConvert.INSTANCE.convertOne(collectEntity);
    }

}