package com.yunzhupaas.base.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunzhupaas.base.entity.BillNumEntity;
import com.yunzhupaas.base.mapper.BillNumMapper;
import com.yunzhupaas.base.service.BillNumService;
import com.yunzhupaas.base.service.SuperServiceImpl;
import com.yunzhupaas.util.RandomUtil;
import com.yunzhupaas.util.StringUtil;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 单据递增序号
 *
 * @author 云筑产品开发平台组
 * @version v5.1.0
 * @copyright 深圳市乐程软件有限公司
 * @date 2024/9/4 9:28:31
 */
@Service
public class BillNumServiceImpl extends SuperServiceImpl<BillNumMapper, BillNumEntity> implements BillNumService {

    public void saveBillNum(BillNumEntity entity) {
        if (entity.getId() == null) {
            entity.setId(RandomUtil.uuId());
        }
        this.saveOrUpdate(entity);
    }

    public BillNumEntity getBillNum(String ruleId, String visualId, String flowId) {
        QueryWrapper<BillNumEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BillNumEntity::getRuleId, ruleId);
        queryWrapper.lambda().eq(BillNumEntity::getVisualId, visualId);
        if (StringUtil.isNotEmpty(flowId)) {
            queryWrapper.lambda().eq(BillNumEntity::getFlowId, flowId);
        } else {
            queryWrapper.lambda().isNull(BillNumEntity::getFlowId);
        }
        List<BillNumEntity> list = this.list(queryWrapper);
        if (list.size() > 0) {
            BillNumEntity billNumEntity = list.stream().findFirst().orElse(null);
            return billNumEntity;
        }
        return null;
    }

    @Override
    public void removeByRuleId(String ruleId, String visualId, String flowId) {
        QueryWrapper<BillNumEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BillNumEntity::getRuleId, ruleId);
        queryWrapper.lambda().eq(BillNumEntity::getVisualId, visualId);
        if (StringUtil.isNotEmpty(flowId)) {
            queryWrapper.lambda().eq(BillNumEntity::getFlowId, flowId);
        } else {
            queryWrapper.lambda().isNull(BillNumEntity::getFlowId);
        }
        this.remove(queryWrapper);
    }
}

