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.MallAttribute;
import org.dromara.mall.product.domain.bo.MallAttributeBo;
import org.dromara.mall.product.domain.vo.MallAttributeVo;
import org.dromara.mall.product.mapper.MallAttributeMapper;
import org.dromara.mall.product.service.MallAttributeService;
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 MallAttributeServiceImpl implements MallAttributeService {

    private final MallAttributeMapper baseMapper;

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

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

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

    /**
     * 根据模板ID查询属性列表
     */
    @Override
    public List<MallAttributeVo> queryListByTemplateId(Long templateId) {
        LambdaQueryWrapper<MallAttribute> lqw = new LambdaQueryWrapper<>();
        lqw.eq(MallAttribute::getTemplateId, templateId);
        lqw.eq(MallAttribute::getStatus, 0);
        lqw.orderByAsc(MallAttribute::getSort);
        lqw.orderByAsc(MallAttribute::getId);
        return baseMapper.selectVoList(lqw);
    }

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

    /**
     * 新增属性
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(MallAttributeBo bo) {
        MallAttribute add = MapstructUtils.convert(bo, MallAttribute.class);
        validEntityBeforeSave(add);

        // 设置默认值
        if (add.getRequired() == null) {
            add.setRequired(0);
        }
        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(MallAttributeBo bo) {
        MallAttribute update = MapstructUtils.convert(bo, MallAttribute.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MallAttribute entity) {
        if (StringUtils.isBlank(entity.getName())) {
            throw new ServiceException("属性名称不能为空");
        }
        if (entity.getType() == null) {
            throw new ServiceException("属性类型不能为空");
        }
        if (entity.getType() < 0 || entity.getType() > 3) {
            throw new ServiceException("属性类型不合法");
        }
        // 检查属性名称是否重复（在同一模板下）
        LambdaQueryWrapper<MallAttribute> lqw = new LambdaQueryWrapper<>();
        lqw.eq(MallAttribute::getName, entity.getName());
        if (entity.getTemplateId() != null) {
            lqw.eq(MallAttribute::getTemplateId, entity.getTemplateId());
        }
        if (entity.getId() != null) {
            lqw.ne(MallAttribute::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) {
                MallAttribute attribute = baseMapper.selectById(id);
                if (attribute == null) {
                    throw new ServiceException("属性不存在");
                }
                // 可以后续添加属性值表关联查询，检查是否有关联的属性值
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
