package com.fjhx.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.base.BaseEntity;
import com.fjhx.constants.LibraryProductLockConstant;
import com.fjhx.constants.ErrorMsgConstant;
import com.fjhx.entity.Product;
import com.fjhx.mapper.ProductMapper;
import com.fjhx.service.ProductService;
import com.fjhx.utils.Assert;
import lombok.RequiredArgsConstructor;
import org.springblade.core.redis.lock.RedisLockClient;
import org.springblade.core.secure.utils.AuthUtil;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 产品 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2022-07-06
 */
@Service
@RequiredArgsConstructor
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    private final RedisLockClient redisLockClient;

    @Override
    public void add(Product product) {
        Assert.notEmpty(product.getName(), "产品名称不能为空");
        Assert.notEmpty(product.getCode(), "产品编码不能为空");

        String tenantId = AuthUtil.getTenantId();
        Boolean flag = redisLockClient.lockFair(LibraryProductLockConstant.PRODUCT_CODE_ONLY_LOCK + tenantId, () -> {
            productCodeOnly(tenantId, product.getCode(), null);
            save(product);
            return true;
        });
        Assert.eqTrue(flag, ErrorMsgConstant.SYSTEM_BUSY_ERROR);
    }

    @Override
    public void edit(Product product) {
        Assert.notEmpty(product.getId(), "产品id不能为空");
        String tenantId = AuthUtil.getTenantId();
        Boolean flag = redisLockClient.lockFair(LibraryProductLockConstant.PRODUCT_CODE_ONLY_LOCK + tenantId, () -> {
            productCodeOnly(tenantId, product.getCode(), product.getId());
            updateById(product);
            return true;
        });
        Assert.eqTrue(flag, ErrorMsgConstant.SYSTEM_BUSY_ERROR);
    }

    @Override
    public void delete(Product product) {
        removeById(product.getId());
    }

    @Override
    public List<String> getUnitList() {
        return baseMapper.getUnitList(AuthUtil.getTenantId());
    }

    /**
     * 检查产品编码是否唯一
     *
     * @param tenantId    租户id
     * @param productCode 产品编码
     * @param excludeId   排除产品id（编辑时不判断自己）
     */
    private void productCodeOnly(String tenantId, String productCode, Long excludeId) {
        Long count = lambdaQuery()
                .eq(BaseEntity::getTenantId, tenantId)
                .eq(Product::getCode, productCode)
                .ne(ObjectUtil.isNotEmpty(excludeId), BaseEntity::getId, excludeId)
                .count();
        Assert.eqZero(count, "产品编码重复，添加失败");
    }

}
