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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seer.teach.common.enums.EntityDeleteFlagEnums;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.mall.convert.GoodConverter;
import com.seer.teach.mall.entity.GoodsEntity;
import com.seer.teach.mall.entity.GoodsSpecificationEntity;
import com.seer.teach.mall.mapper.GoodsMapper;
import com.seer.teach.mall.response.GoodsResp;
import com.seer.teach.mall.service.IGoodsService;
import com.seer.teach.mall.service.IGoodsSpecificationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@RequiredArgsConstructor
@Slf4j
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, GoodsEntity> implements IGoodsService {

    private final IGoodsSpecificationService goodsSpecificationService;

    @Override
    public IPage<GoodsEntity> queryPageList(Integer size, Integer current, GoodsEntity goods) {
        IPage<GoodsEntity> pageParams = new Page<>(current,size);
        IPage<GoodsEntity> iPage = super.getBaseMapper().selectPage(pageParams, new LambdaQueryWrapper<GoodsEntity>()
                .like(StringUtils.isNotBlank(goods.getName()),GoodsEntity::getName,goods.getName())
                .eq(Objects.nonNull(goods.getIsOnSale()),GoodsEntity::getIsOnSale,goods.getIsOnSale())
                .eq(Objects.nonNull(goods.getMerchantUserId()),GoodsEntity::getMerchantUserId,goods.getMerchantUserId())
                .eq(Objects.nonNull(goods.getStatus()),GoodsEntity::getStatus,goods.getStatus())
                .eq(Objects.nonNull(goods.getTenantId()),GoodsEntity::getTenantId,goods.getTenantId())
                .orderByDesc(GoodsEntity::getId));
        log.info("查询商品列表总数：{}", iPage.getTotal());
        return iPage;
    }

    @Override
    public GoodsResp queryDetail(Integer id) {
        GoodsEntity goodsEntity = getById(id);
        AssertUtils.notNull(goodsEntity, ResultCodeEnum.GOOD_NOT_FOUND);
        List<GoodsSpecificationEntity> list = goodsSpecificationService.list(new LambdaQueryWrapper<>(GoodsSpecificationEntity.class).eq(GoodsSpecificationEntity::getGoodsId, id));
        return GoodConverter.INSTANCE.one(goodsEntity,list);
    }

    @Override
    public int batchUpdateSaleByIds(List<Integer> idList, Integer userId, GoodsEntity goods) {
        return super.getBaseMapper().batchUpdateSaleByIds(idList,userId,goods);
    }

    @Override
    public int updateDeleteBatchByIds(EntityDeleteFlagEnums deleteFlagEnums, List<Integer> ids,Integer userId) {
        GoodsEntity goodsEntity = new GoodsEntity();
        goodsEntity.setUpdateBy(String.valueOf(userId));
        goodsEntity.setUpdateTime(LocalDateTime.now());
        return super.getBaseMapper().updateDeleteBatchByIds(deleteFlagEnums.getCode(),ids,goodsEntity);
    }

    @Override
    public void increaseCollectCount(Integer goodsId) {
        super.update(null, new LambdaUpdateWrapper<GoodsEntity>()
                .eq(GoodsEntity::getId, goodsId)
                .setSql("collect_count = IFNULL(collect_count, 0) + 1")
        );
    }

    @Override
    public void decreaseCollectCount(Integer goodsId) {
        super.update(null, new LambdaUpdateWrapper<GoodsEntity>()
                .eq(GoodsEntity::getId, goodsId)
                .setSql("collect_count = IFNULL(collect_count, 0) - 1")
        );
    }

    @Override
    public boolean updateSellVolumeAndStock(Set<Integer> goodsIdList, Integer volume) {
        List<GoodsEntity> goodList = super.listByIds(goodsIdList);
        goodList.forEach(goods -> {
            Long salesCount = goods.getSalesCount();
            if(Objects.isNull(salesCount)){
                salesCount = 0L;
            }
            goods.setSalesCount(salesCount + volume);
            Long stock = goods.getStock();
            if(Objects.isNull(stock)){
                stock = 1L;
            }
            goods.setStock(stock - volume);
        });
        return super.updateBatchById(goodList);
    }
}
