package cn.iocoder.foodnexus.module.order.service.shoppingcart;

import cn.iocoder.foodnexus.framework.common.util.CommonUtil;
import cn.iocoder.foodnexus.module.order.controller.app.shoppingcart.vo.ShoppingCartPageReqVO;
import cn.iocoder.foodnexus.module.order.controller.app.shoppingcart.vo.ShoppingCartSaveBatchReqVO;
import cn.iocoder.foodnexus.module.order.controller.app.shoppingcart.vo.ShoppingCartSaveReqVO;
import cn.iocoder.foodnexus.module.product.dal.dataobject.spu.ProductSpuDO;
import cn.iocoder.foodnexus.module.product.enums.spu.ProductSpuStatusEnum;
import cn.iocoder.foodnexus.module.product.service.spu.ProductSpuService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.foodnexus.module.order.dal.dataobject.shoppingcart.ShoppingCartDO;
import cn.iocoder.foodnexus.framework.common.pojo.PageResult;
import cn.iocoder.foodnexus.framework.common.util.object.BeanUtils;

import cn.iocoder.foodnexus.module.order.dal.mysql.shoppingcart.ShoppingCartMapper;

import static cn.iocoder.foodnexus.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.foodnexus.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.foodnexus.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.foodnexus.module.order.enums.ErrorCodeConstants.*;

/**
 * 购物车 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private ProductSpuService productSpuService;

    @Override
    public Long createShoppingCart(ShoppingCartSaveReqVO createReqVO) {
        validProduct(createReqVO.getProductId());
        ShoppingCartDO cart = shoppingCartMapper.selectOne(Wrappers.<ShoppingCartDO>lambdaQuery()
                .eq(ShoppingCartDO::getProductId, createReqVO.getProductId())
                .eq(ShoppingCartDO::getCreator, getLoginUserId())
                .last("LIMIT 1"));
        if (CommonUtil.isNotEmpty(cart)) {
            ShoppingCartDO updateCart = new ShoppingCartDO();
            updateCart.setId(cart.getId());
            updateCart.setRemark(createReqVO.getRemark());
            updateCart.setOrderQuantity(cart.getOrderQuantity() + createReqVO.getOrderQuantity());
            shoppingCartMapper.updateById(updateCart);
            return cart.getId();
        }
        // 插入
        ShoppingCartDO shoppingCart = BeanUtils.toBean(createReqVO, ShoppingCartDO.class);
        shoppingCartMapper.insert(shoppingCart);

        // 返回
        return shoppingCart.getId();
    }

    private void validProduct(Long productId) {
        ProductSpuDO appSpu = productSpuService.getAppSpu(productId);
        if (CommonUtil.isEmpty(appSpu) || !ProductSpuStatusEnum.isEnable(appSpu.getStatus()) ){
            throw exception(PRODUCT_DISABLE, appSpu.getName());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createBatch(ShoppingCartSaveBatchReqVO createReqVO) {
        List<ProductSpuDO> spuList = productSpuService.getSpuList(CommonUtil.listConvert(createReqVO.getItems(), ShoppingCartSaveReqVO::getProductId));
        if (CommonUtil.isEmpty(spuList)) {
            throw exception(PRODUCT_NO_EXISTS);
        }
        List<ProductSpuDO> collect = spuList.stream().filter(item -> ProductSpuStatusEnum.isEnable(item.getStatus())).toList();
        if (CommonUtil.isEmpty(collect)) {
            throw exception(PRODUCT_DISABLE, String.join(",", CommonUtil.listConvertSet(createReqVO.getItems(), ShoppingCartSaveReqVO::getProductName)));
        }
        List<Long> productIds = CommonUtil.listConvert(collect, ProductSpuDO::getId);
        for (ShoppingCartSaveReqVO item : createReqVO.getItems()) {
            if (productIds.contains(item.getProductId())) {
                this.createShoppingCart(item);
            }
        }
    }

    @Override
    public void updateShoppingCart(ShoppingCartSaveReqVO updateReqVO) {
        // 校验存在
        validateShoppingCartExists(updateReqVO.getId());
        validProduct(updateReqVO.getProductId());
        // 更新
        ShoppingCartDO updateObj = BeanUtils.toBean(updateReqVO, ShoppingCartDO.class);
        shoppingCartMapper.updateById(updateObj);
    }

    @Override
    public void deleteShoppingCart(Long id) {
        // 校验存在
        validateShoppingCartExists(id);
        // 删除
        shoppingCartMapper.deleteById(id);
    }

    @Override
        public void deleteShoppingCartListByIds(List<Long> ids) {
        // 删除
        shoppingCartMapper.deleteByIds(ids);
        }


    private void validateShoppingCartExists(Long id) {
        if (shoppingCartMapper.selectById(id) == null) {
            throw exception(SHOPPING_CART_NOT_EXISTS);
        }
    }

    @Override
    public ShoppingCartDO getShoppingCart(Long id) {
        return shoppingCartMapper.selectById(id);
    }

    @Override
    public PageResult<ShoppingCartDO> getShoppingCartPage(ShoppingCartPageReqVO pageReqVO) {
        return shoppingCartMapper.selectPage(pageReqVO);
    }

    @Override
    public Map<Long, ShoppingCartDO> getMap(Long creator, List<Long> productIds) {
        List<ShoppingCartDO> shoppingCartDOS = shoppingCartMapper.selectList(Wrappers.<ShoppingCartDO>lambdaQuery()
                .in(ShoppingCartDO::getProductId, productIds)
                .eq(ShoppingCartDO::getCreator, creator));
        return CommonUtil.listConvertMap(shoppingCartDOS, ShoppingCartDO::getProductId);
    }

    @Override
    public void deleteByProductId(Long creator, List<Long> productIds) {
        if (CommonUtil.isEmpty(productIds)) {
            return;
        }
        shoppingCartMapper.delete(Wrappers.<ShoppingCartDO>lambdaQuery()
                .in(ShoppingCartDO::getProductId, productIds)
                .eq(ShoppingCartDO::getCreator, creator));
    }

}