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.ErrorMsgConstant;
import com.fjhx.constants.LibraryProductLockConstant;
import com.fjhx.entity.Material;
import com.fjhx.mapper.MaterialMapper;
import com.fjhx.service.MaterialService;
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 MaterialServiceImpl extends ServiceImpl<MaterialMapper, Material> implements MaterialService {

    private final RedisLockClient redisLockClient;

    @Override
    public void add(Material material) {
        Assert.notEmpty(material.getName(), "物料名称不能为空");
        Assert.notEmpty(material.getCode(), "物料编码不能为空");

        String tenantId = AuthUtil.getTenantId();

        // 保证每个租户物料编码唯一
        Boolean flag = redisLockClient.lockFair(LibraryProductLockConstant.MATERIAL_CODE_ONLY_LOCK + tenantId,
                () -> {
                    // 判断物料编码是否唯一
                    materialCodeOnly(tenantId, material.getCode(), null);
                    save(material);
                    return true;
                });

        Assert.eqTrue(flag, ErrorMsgConstant.SYSTEM_BUSY_ERROR);
    }

    @Override
    public void edit(Material material) {
        String tenantId = AuthUtil.getTenantId();

        // 保证每个租户物料编码唯一
        Boolean flag = redisLockClient.lockFair(LibraryProductLockConstant.MATERIAL_CODE_ONLY_LOCK + tenantId,
                () -> {
                    // 判断物料编码是否唯一
                    materialCodeOnly(tenantId, material.getCode(), material.getId());
                    updateById(material);
                    return true;
                });

        Assert.eqTrue(flag, ErrorMsgConstant.SYSTEM_BUSY_ERROR);
    }

    @Override
    public void delete(Material material) {
        removeById(material.getId());
    }

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

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

}
