package com.fjhx.service.product.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.base.BaseEntity;
import com.fjhx.entity.product.ProductInfo;
import com.fjhx.entity.product.ProductSpu;
import com.fjhx.mapper.product.ProductSpuMapper;
import com.fjhx.params.product.ProductSpuVo;
import com.fjhx.service.product.ProductInfoService;
import com.fjhx.service.product.ProductSpuService;
import com.fjhx.uitl.code.CodeEnum;
import com.fjhx.utils.Assert;
import com.fjhx.utils.wrapperUtil.IWrapper;
import com.fjhx.utils.wrapperUtil.KeywordData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2022-11-25
 */
@Service
public class ProductSpuServiceImpl extends ServiceImpl<ProductSpuMapper, ProductSpu> implements ProductSpuService {

    @Autowired
    private ProductInfoService productInfoService;

    @Override
    public Page<ProductSpu> getPage(Map<String, Object> condition) {
        IWrapper<ProductSpu> wrapper = IWrapper.getWrapper(condition);
        wrapper.keyword(new KeywordData(ProductSpu::getName), new KeywordData(ProductSpu::getCode))
                .orderByDesc(ProductSpu::getId);
        return page(condition, wrapper);
    }

    @Override
    public void add(ProductSpuVo productSpuVo) {
        synchronized (this) {
            productSpuVo.setCode(CodeEnum.SPU.getCode(productSpuVo.getCode()));
            save(productSpuVo);
        }
        resetBindingProduct(productSpuVo.getId(), productSpuVo.getProductIdList());
    }

    @Override
    public void edit(ProductSpuVo productSpuVo) {
        updateById(productSpuVo);
        resetBindingProduct(productSpuVo.getId(), productSpuVo.getProductIdList());
    }

    @Override
    public void delete(ProductSpuVo productSpuVo) {
        // long count = productInfoService.count(q -> q
        //         .eq(ProductInfo::getProductSpuId, productSpuVo.getId()));
        // Assert.eqZero(count, "此spu已关联产品，无法删除");

        removeById(productSpuVo.getId());
    }


    private void resetBindingProduct(Long spuId, List<Long> productIdList) {

        Assert.notEmpty(spuId, "spuId不能为空");

        // 移除spu不属于产品id列表的产品的绑定
        productInfoService.update(q -> q
                .eq(ProductInfo::getProductSpuId, spuId)
                .notIn(ObjectUtil.isNotEmpty(productIdList), BaseEntity::getId, productIdList)
                .set(ProductInfo::getProductSpuId, null)
        );

        // 添加sup与产品绑定
        if (ObjectUtil.isNotEmpty(productIdList)) {
            productInfoService.update(q -> q
                    .in(BaseEntity::getId, productIdList)
                    .set(ProductInfo::getProductSpuId, spuId)
            );
        }

    }

}
