package com.ruoyi.web.stock.service.impl;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.stock.domain.WarehouseBase;
import com.ruoyi.web.stock.domain.vo.StockOptionVo;
import com.ruoyi.web.stock.mapper.WarehouseBaseMapper;
import com.ruoyi.web.stock.service.IWarehouseBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Pattern;

/**
 * 仓库基础设置 Service 实现。
 */
@Service
public class WarehouseBaseServiceImpl implements IWarehouseBaseService {
    private static final Pattern POSITIVE_DIGIT_WITH_LEADING_ZERO = Pattern.compile("^0*[1-9]\\d*$");

    @Autowired
    private WarehouseBaseMapper warehouseBaseMapper;

    @Override
    public WarehouseBase selectById(Long id) {
        return warehouseBaseMapper.selectWarehouseBaseById(id);
    }

    @Override
    public List<WarehouseBase> selectList(WarehouseBase query) {
        return warehouseBaseMapper.selectWarehouseBaseList(query);
    }

    @Override
    public int insert(WarehouseBase entity) {
        if (entity.getIsCentral() == null) {
            entity.setIsCentral(0);
        }
        entity.setDelFlag("0");
        return warehouseBaseMapper.insertWarehouseBase(entity);
    }

    @Override
    public int update(WarehouseBase entity) {
        if (entity.getIsCentral() == null) {
            entity.setIsCentral(0);
        }
        return warehouseBaseMapper.updateWarehouseBase(entity);
    }

    @Override
    public int removeById(Long id) {
        return warehouseBaseMapper.deleteWarehouseBaseById(id);
    }

    @Override
    public List<StockOptionVo> listOptions(String orgId) {
        return warehouseBaseMapper.selectWarehouseOptions(orgId);
    }

    @Override
    public boolean checkWarehouseNoUnique(WarehouseBase entity, String orgId) {
        if (StringUtils.isEmpty(entity.getWarehouseNo())) {
            return true;
        }
        WarehouseBase old = warehouseBaseMapper.selectWarehouseBaseByNo(entity.getWarehouseNo().trim(), orgId);
        if (old == null) {
            return true;
        }
        Long currentId = entity.getId() == null ? -1L : entity.getId();
        return old.getId().longValue() == currentId.longValue();
    }

    @Override
    public boolean checkWarehouseNoValid(String warehouseNo) {
        if (StringUtils.isEmpty(warehouseNo)) {
            return false;
        }
        return POSITIVE_DIGIT_WITH_LEADING_ZERO.matcher(warehouseNo.trim()).matches();
    }
}
