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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.mall.product.domain.MallProductAttribute;
import org.dromara.mall.product.domain.bo.MallProductAttributeBo;
import org.dromara.mall.product.domain.vo.MallProductAttributeVo;
import org.dromara.mall.product.mapper.MallProductAttributeMapper;
import org.dromara.mall.product.service.MallProductAttributeService;
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 MallProductAttributeServiceImpl implements MallProductAttributeService {

    private final MallProductAttributeMapper baseMapper;

    /**
     * 查询商品属性关联
     */
    @Override
    public MallProductAttributeVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 根据商品ID查询商品属性关联列表
     */
    @Override
    public List<MallProductAttributeVo> queryListByProductId(Long productId) {
        LambdaQueryWrapper<MallProductAttribute> lqw = new LambdaQueryWrapper<>();
        lqw.eq(MallProductAttribute::getProductId, productId);
        lqw.orderByAsc(MallProductAttribute::getId);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 新增商品属性关联
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(MallProductAttributeBo bo) {
        MallProductAttribute add = MapstructUtils.convert(bo, MallProductAttribute.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 批量新增商品属性关联
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertBatch(List<MallProductAttributeBo> list) {
        if (list == null || list.isEmpty()) {
            return true;
        }
        List<MallProductAttribute> entities = MapstructUtils.convert(list, MallProductAttribute.class);
        for (MallProductAttribute entity : entities) {
            validEntityBeforeSave(entity);
        }
        // 批量插入
        for (MallProductAttribute entity : entities) {
            baseMapper.insert(entity);
        }
        return true;
    }

    /**
     * 修改商品属性关联
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(MallProductAttributeBo bo) {
        MallProductAttribute update = MapstructUtils.convert(bo, MallProductAttribute.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MallProductAttribute entity) {
        if (entity.getProductId() == null) {
            throw new ServiceException("商品ID不能为空");
        }
        if (entity.getAttributeId() == null) {
            throw new ServiceException("属性ID不能为空");
        }
        // 检查同一商品下是否已有相同的属性
        LambdaQueryWrapper<MallProductAttribute> lqw = new LambdaQueryWrapper<>();
        lqw.eq(MallProductAttribute::getProductId, entity.getProductId());
        lqw.eq(MallProductAttribute::getAttributeId, entity.getAttributeId());
        if (entity.getId() != null) {
            lqw.ne(MallProductAttribute::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) {
                MallProductAttribute attribute = baseMapper.selectById(id);
                if (attribute == null) {
                    throw new ServiceException("商品属性关联不存在");
                }
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 根据商品ID删除商品属性关联
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteByProductId(Long productId) {
        LambdaQueryWrapper<MallProductAttribute> lqw = new LambdaQueryWrapper<>();
        lqw.eq(MallProductAttribute::getProductId, productId);
        return baseMapper.delete(lqw) >= 0;
    }

    /**
     * 保存商品属性关联（先删除旧的，再插入新的）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveProductAttributes(Long productId, List<MallProductAttributeBo> list) {
        // 删除旧的关联
        deleteByProductId(productId);
        // 插入新的关联
        if (list != null && !list.isEmpty()) {
            for (MallProductAttributeBo bo : list) {
                bo.setProductId(productId);
            }
            return insertBatch(list);
        }
        return true;
    }
}
