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.MallBrand;
import org.dromara.mall.product.domain.bo.MallBrandBo;
import org.dromara.mall.product.domain.vo.MallBrandVo;
import org.dromara.mall.product.mapper.MallBrandMapper;
import org.dromara.mall.product.service.MallBrandService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 品牌Service业务层处理
 *
 * @author pengles
 */
@RequiredArgsConstructor
@Service
public class MallBrandServiceImpl implements MallBrandService {

    private final MallBrandMapper baseMapper;

    /**
     * 查询品牌
     */
    @Override
    public MallBrandVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询品牌列表
     */
    @Override
    public TableDataInfo<MallBrandVo> queryPageList(MallBrandBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MallBrand> lqw = buildQueryWrapper(bo);
        Page<MallBrandVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询品牌列表
     */
    @Override
    public List<MallBrandVo> queryList(MallBrandBo bo) {
        LambdaQueryWrapper<MallBrand> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

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

    /**
     * 新增品牌
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(MallBrandBo bo) {
        MallBrand add = MapstructUtils.convert(bo, MallBrand.class);
        validEntityBeforeSave(add);

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

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

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

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MallBrand entity) {
        if (StringUtils.isBlank(entity.getName())) {
            throw new ServiceException("品牌名称不能为空");
        }
        // 检查品牌名称是否重复
        LambdaQueryWrapper<MallBrand> lqw = new LambdaQueryWrapper<>();
        lqw.eq(MallBrand::getName, entity.getName());
        if (entity.getId() != null) {
            lqw.ne(MallBrand::getId, entity.getId());
        }
        Long count = baseMapper.selectCount(lqw);
        if (count > 0) {
            throw new ServiceException("品牌名称已存在");
        }
    }

    /**
     * 批量删除品牌
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 检查是否有关联的商品（这里需要关联商品表查询，暂时跳过）
            // 可以后续添加商品表关联查询
            for (Long id : ids) {
                MallBrand brand = baseMapper.selectById(id);
                if (brand == null) {
                    throw new ServiceException("品牌不存在");
                }
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
