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.MallAttributeValue;
import org.dromara.mall.product.domain.bo.MallAttributeValueBo;
import org.dromara.mall.product.domain.vo.MallAttributeValueVo;
import org.dromara.mall.product.mapper.MallAttributeValueMapper;
import org.dromara.mall.product.service.MallAttributeValueService;
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 MallAttributeValueServiceImpl implements MallAttributeValueService {

    private final MallAttributeValueMapper baseMapper;

    /**
     * 查询属性值
     */
    @Override
    public MallAttributeValueVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询属性值列表
     */
    @Override
    public TableDataInfo<MallAttributeValueVo> queryPageList(MallAttributeValueBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MallAttributeValue> lqw = buildQueryWrapper(bo);
        Page<MallAttributeValueVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询属性值列表
     */
    @Override
    public List<MallAttributeValueVo> queryList(MallAttributeValueBo bo) {
        LambdaQueryWrapper<MallAttributeValue> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据属性ID查询属性值列表
     */
    @Override
    public List<MallAttributeValueVo> queryListByAttributeId(Long attributeId) {
        LambdaQueryWrapper<MallAttributeValue> lqw = new LambdaQueryWrapper<>();
        lqw.eq(MallAttributeValue::getAttributeId, attributeId);
        lqw.eq(MallAttributeValue::getStatus, 0);
        lqw.orderByAsc(MallAttributeValue::getSort);
        lqw.orderByAsc(MallAttributeValue::getId);
        return baseMapper.selectVoList(lqw);
    }

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

    /**
     * 新增属性值
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(MallAttributeValueBo bo) {
        MallAttributeValue add = MapstructUtils.convert(bo, MallAttributeValue.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(MallAttributeValueBo bo) {
        MallAttributeValue update = MapstructUtils.convert(bo, MallAttributeValue.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MallAttributeValue entity) {
        if (entity.getAttributeId() == null) {
            throw new ServiceException("属性ID不能为空");
        }
        if (StringUtils.isBlank(entity.getValue())) {
            throw new ServiceException("属性值不能为空");
        }
        // 检查属性值是否重复（在同一属性下）
        LambdaQueryWrapper<MallAttributeValue> lqw = new LambdaQueryWrapper<>();
        lqw.eq(MallAttributeValue::getAttributeId, entity.getAttributeId());
        lqw.eq(MallAttributeValue::getValue, entity.getValue());
        if (entity.getId() != null) {
            lqw.ne(MallAttributeValue::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) {
                MallAttributeValue value = baseMapper.selectById(id);
                if (value == null) {
                    throw new ServiceException("属性值不存在");
                }
                // 可以后续添加商品属性关联表查询，检查是否有关联的商品属性
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
