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

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.common.utils.PageConverterUtils;
import com.seer.teach.mall.app.good.service.IAppGoodsSpecificationService;
import com.seer.teach.mall.app.order.service.IAppCartService;
import com.seer.teach.mall.convert.CartConvert;
import com.seer.teach.mall.entity.CartEntity;
import com.seer.teach.mall.entity.GoodsEntity;
import com.seer.teach.mall.entity.GoodsSpecificationEntity;
import com.seer.teach.mall.mapper.CartMapper;
import com.seer.teach.mall.request.CartPageReq;
import com.seer.teach.mall.request.CartSaveReq;
import com.seer.teach.mall.request.CartUpdateReq;
import com.seer.teach.mall.response.CartResp;
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.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 *  w购物车服务实现类
 * </p>
 *
 * @author Captain
 * @since 2025-06-10
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AppCartServiceImpl extends ServiceImpl<CartMapper, CartEntity> implements IAppCartService {

    private final IGoodsService goodsService;

    private final IAppGoodsSpecificationService goodsSpecificationService;

    @Override
    public PageListBean<CartResp> getCartList(CartPageReq params) {
        // 获取当前登录用户ID
        Integer userId = StpUtil.getLoginIdAsInt();
        // 创建分页对象
        Page<CartEntity> page = new Page<>(params.getPageNo(), params.getPageSize());
        Page<CartEntity> resultPage = this.page(page,
                Wrappers.lambdaQuery(CartEntity.class)
                        .eq(CartEntity::getUserId, userId));

        if(CollectionUtils.isEmpty(resultPage.getRecords())){
            return new PageListBean<>();
        }
        Set<Integer> skuIdList = resultPage.getRecords().stream().map(CartEntity::getSkuId).collect(Collectors.toSet());

        List<GoodsSpecificationEntity> goodsSpecificationEntities = goodsSpecificationService.listByIds(skuIdList);
        AssertUtils.notEmpty(goodsSpecificationEntities, ResultCodeEnum.GOOD_SPECIFICATIONS_NOT_EXIST);

        Map<Integer, GoodsSpecificationEntity> specificationEntityMap = goodsSpecificationEntities.stream().collect(Collectors.toMap(GoodsSpecificationEntity::getId, Function.identity(), (old, newItem) -> newItem));
        PageListBean<CartResp> cartRespPageList = PageConverterUtils.convertPageListBean(resultPage, CartConvert.INSTANCE::convertList);
        cartRespPageList.getList().forEach(cartResp -> {
            GoodsSpecificationEntity sku = specificationEntityMap.get(cartResp.getSkuId());
            cartResp.setPicUrl(sku.getPicUrl());
            cartResp.setPrice(sku.getPrice());
            cartResp.setAttributeList(sku.getAttributes());
        });
        return cartRespPageList;
    }


    @Override
    public boolean updateCart(CartUpdateReq params) {
        // 获取当前登录用户ID
        Integer userId = StpUtil.getLoginIdAsInt();
        // 创建更新条件
        LambdaUpdateWrapper<CartEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CartEntity::getUserId, userId)
                .eq(CartEntity::getId, params.getId())
                .eq(CartEntity::getSkuId,params.getSkuId())
                .set(CartEntity::getNumber, params.getNumber());
        // 执行更新操作
        return super.update(null, updateWrapper);
    }

    /**
     * 购物车数量信息删除
     *
     * @param ids 要删除的商品ID
     * Time: 2025/6/18 20:38
     */
    @Override
    public boolean deleteCart(List<Integer> ids) {
        List<CartEntity> cartEntityList = super.listByIds(ids);
        if(CollectionUtils.isEmpty(cartEntityList)){
            return false;
        }
        //获取当前登录用户的ID
        Integer userId = StpUtil.getLoginIdAsInt();
        List<CartEntity> userGoodsCollectList = cartEntityList.stream().filter(goodsCollect -> goodsCollect.getUserId().equals(userId)).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(userGoodsCollectList)){
            return false;
        }
        boolean update = removeBatchByIds(userGoodsCollectList);
        log.info("删除购物车结果:{}", update);
        return update;
    }

    /**
     * 购物车商品添加请求
     *
     * @param params 添加请求参数
     * Time: 2025/6/18 20:39
     */
    @Override
    public boolean saveCart(CartSaveReq params) {
        log.debug("添加购物车参数: 商品ID={}, 规格ID={}", params.getGoodsId(), params.getSkuId());
        GoodsEntity goods = goodsService.getById(params.getGoodsId());
        AssertUtils.notNull(goods, ResultCodeEnum.GOOD_NOT_FOUND);
        GoodsSpecificationEntity specification = goodsSpecificationService.getById(params.getSkuId());
        AssertUtils.notNull(specification, ResultCodeEnum.GOOD_SPECIFICATIONS_NOT_EXIST);
        // 获取当前登录用户ID
        Integer userId = StpUtil.getLoginIdAsInt();
        CartEntity exist = this.getOne(new LambdaQueryWrapper<CartEntity>()
                .eq(CartEntity::getUserId, userId)
                .eq(CartEntity::getGoodsId, params.getGoodsId())
                .eq(CartEntity::getSkuId, params.getSkuId()));
        if (exist != null) {
            // 如果存在，更新数量
            exist.setNumber(exist.getNumber() + params.getNumber());
            return updateById(exist);
        } else {
            // 如果不存在，新建购物车记录
            CartEntity cartEntity = new CartEntity();
            cartEntity.setUserId(userId);
            cartEntity.setGoodsId(params.getGoodsId());
            cartEntity.setGoodsName(goods.getName());
            cartEntity.setSkuId(params.getSkuId());
            cartEntity.setNumber(params.getNumber());
            return save(cartEntity);
        }
    }
}
