package org.dromara.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.mall.product.domain.MallSku;
import org.dromara.mall.product.domain.bo.MallSkuBo;
import org.dromara.mall.product.domain.vo.MallSkuVo;
import org.dromara.mall.product.mapper.MallSkuMapper;
import org.dromara.mall.product.service.MallSkuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * SKU Service业务层处理
 *
 * @author pengles
 */
@RequiredArgsConstructor
@Service
public class MallSkuServiceImpl implements MallSkuService {

    private final MallSkuMapper baseMapper;

    /**
     * 查询SKU
     */
    @Override
    public MallSkuVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询SKU列表
     */
    @Override
    public TableDataInfo<MallSkuVo> queryPageList(MallSkuBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MallSku> lqw = buildQueryWrapper(bo);
        Page<MallSkuVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询SKU列表
     */
    @Override
    public List<MallSkuVo> queryList(MallSkuBo bo) {
        LambdaQueryWrapper<MallSku> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据商品ID查询SKU列表
     */
    @Override
    public List<MallSkuVo> queryListByProductId(Long productId) {
        LambdaQueryWrapper<MallSku> lqw = new LambdaQueryWrapper<>();
        lqw.eq(MallSku::getProductId, productId);
        lqw.eq(MallSku::getStatus, 0); // 只查询启用的SKU
        lqw.orderByAsc(MallSku::getId);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MallSku> buildQueryWrapper(MallSkuBo bo) {
        LambdaQueryWrapper<MallSku> lqw = new LambdaQueryWrapper<>();
        lqw.eq(bo.getProductId() != null, MallSku::getProductId, bo.getProductId());
        lqw.eq(StringUtils.isNotBlank(bo.getSkuCode()), MallSku::getSkuCode, bo.getSkuCode());
        lqw.like(StringUtils.isNotBlank(bo.getName()), MallSku::getName, bo.getName());
        lqw.eq(bo.getStatus() != null, MallSku::getStatus, bo.getStatus());
        lqw.orderByAsc(MallSku::getId);
        return lqw;
    }

    /**
     * 新增SKU
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(MallSkuBo bo) {
        MallSku add = MapstructUtils.convert(bo, MallSku.class);
        validEntityBeforeSave(add);

        // 设置默认值
        if (add.getStock() == null) {
            add.setStock(0);
        }
        if (add.getStatus() == null) {
            add.setStatus(0);
        }

        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改SKU
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(MallSkuBo bo) {
        MallSku update = MapstructUtils.convert(bo, MallSku.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MallSku entity) {
        if (entity.getProductId() == null) {
            throw new ServiceException("商品ID不能为空");
        }
        if (StringUtils.isBlank(entity.getSkuCode())) {
            throw new ServiceException("SKU编码不能为空");
        }
        if (entity.getPrice() == null) {
            throw new ServiceException("价格不能为空");
        }
        // 检查SKU编码是否重复
        LambdaQueryWrapper<MallSku> lqw = new LambdaQueryWrapper<>();
        lqw.eq(MallSku::getSkuCode, entity.getSkuCode());
        if (entity.getId() != null) {
            lqw.ne(MallSku::getId, entity.getId());
        }
        Long count = baseMapper.selectCount(lqw);
        if (count > 0) {
            throw new ServiceException("SKU编码已存在");
        }
    }

    /**
     * 批量删除SKU
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            for (Long id : ids) {
                MallSku sku = baseMapper.selectById(id);
                if (sku == null) {
                    throw new ServiceException("SKU不存在");
                }
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}