package com.seer.teach.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.enums.GoodsAttributeScopeEnum;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.common.utils.PageConverterUtils;
import com.seer.teach.mall.convert.GoodsAttributeConvert;
import com.seer.teach.mall.entity.GoodsAttributeEntity;
import com.seer.teach.mall.entity.GoodsSpecificationEntity;
import com.seer.teach.mall.mapper.GoodsAttributeMapper;
import com.seer.teach.mall.request.GoodsAttributePageReq;
import com.seer.teach.mall.request.GoodsAttributeReq;
import com.seer.teach.mall.response.GoodsAttributeResq;
import com.seer.teach.mall.service.IGoodsAttributeService;
import com.seer.teach.mall.service.IGoodsSpecificationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Captain
 * @since 2025-06-10
 */
@RequiredArgsConstructor
@Slf4j
@Service
public class GoodsAttributeServiceImpl extends ServiceImpl<GoodsAttributeMapper, GoodsAttributeEntity> implements IGoodsAttributeService {

    private final IGoodsSpecificationService goodsSpecificationService;

    @Override
    public PageListBean<GoodsAttributeResq> getAttributePage(GoodsAttributePageReq pageReq) {
        // 构建分页参数
        Page<GoodsAttributeEntity> page = new Page<>(pageReq.getPageNo(), pageReq.getPageSize());

        LambdaQueryWrapper<GoodsAttributeEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(pageReq.getAttributeName() != null, GoodsAttributeEntity::getAttributeName, pageReq.getAttributeName())
                .eq(pageReq.getStatus() != null, GoodsAttributeEntity::getStatus, pageReq.getStatus());

        // 如果指定了scope，则按指定scope查询
        if (pageReq.getScope() != null) {
            queryWrapper.eq(GoodsAttributeEntity::getScope, pageReq.getScope());
        }
        // 如果指定了merchantId，则添加merchantId过滤条件
        if (pageReq.getMerchantId() != null) {
            queryWrapper.and(wrapper -> wrapper.eq(GoodsAttributeEntity::getScope, GoodsAttributeScopeEnum.PLATFORM)
                    .or()
                    .eq(GoodsAttributeEntity::getMerchantId, pageReq.getMerchantId()));
        }

        // 执行分页查询
        IPage<GoodsAttributeEntity> attributePage = super.page(page, queryWrapper);

        return PageConverterUtils.convertPageListBean(attributePage, GoodsAttributeConvert.INSTANCE::convertList);
    }

    @Override
    public GoodsAttributeResq getAttributeInfo(Integer id) {
        GoodsAttributeEntity attribute = getById(id);
        return GoodsAttributeConvert.INSTANCE.convertOne( attribute);
    }

    @Override
    public boolean saveAttribute(GoodsAttributeReq params) {
        // 检查属性名称是否已存在
        long count = super.count(new LambdaQueryWrapper<GoodsAttributeEntity>()
                .eq(GoodsAttributeEntity::getAttributeName, params.getAttributeName()));

        AssertUtils.isTrue(count == 0, ResultCodeEnum.GOODS_ATTRIBUTE_NAME_IS_REPEATED);

        return save( GoodsAttributeConvert.INSTANCE.convertOne( params));
    }

    @Override
    public boolean updateAttribute(GoodsAttributeReq params) {

        // 检查属性是否存在
        GoodsAttributeEntity existing = getById(params.getId());

        AssertUtils.notNull(existing, ResultCodeEnum.GOODS_ATTRIBUTE_EXISTS);

        // 检查属性名称是否与其他记录重复
        long count = count(new LambdaQueryWrapper<GoodsAttributeEntity>()
                .eq(GoodsAttributeEntity::getAttributeName, params.getAttributeName())
                .ne(GoodsAttributeEntity::getId, params.getId()));


        AssertUtils.isTrue(count == 0, ResultCodeEnum.GOODS_ATTRIBUTE_NAME_IS_USED);

        // 使用LambdaUpdateWrapper进行更新
        LambdaUpdateWrapper<GoodsAttributeEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(GoodsAttributeEntity::getId, params.getId())
                .set(params.getAttributeName() != null, GoodsAttributeEntity::getAttributeName, params.getAttributeName())
                .set(params.getStatus() != null, GoodsAttributeEntity::getStatus, params.getStatus());

        GoodsAttributeEntity goodsAttributeEntity = GoodsAttributeConvert.INSTANCE.convertOne(params);
        return super.update(goodsAttributeEntity, updateWrapper);
    }

    @Override
    public boolean deleteAttribute(List<Integer> ids) {
        // 查询是否有商品规格关联了这些属性
        for (Integer attributeId : ids) {
            // 使用LambdaQueryWrapper查询包含指定attributeId的记录
            long count = goodsSpecificationService.count(new LambdaQueryWrapper<GoodsSpecificationEntity>()
                    .apply("JSON_CONTAINS(attributes, JSON_OBJECT('attributeId', {0}))", attributeId));
            AssertUtils.isTrue(count == 0, ResultCodeEnum.GOODS_ATTRIBUTE_IN_USE);
        }

        return super.removeBatchByIds(ids);
    }
}