package com.bs.jxc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bs.common.utils.DateUtils;
import com.bs.common.utils.StringUtils;
import com.bs.jxc.mapper.CkBillNumberMapper;
import com.bs.jxc.domain.CkBillNumber;
import com.bs.jxc.service.ICkBillNumberService;
import com.github.yulichang.base.MPJBaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 单据编号表Service业务层处理
 *
 * @author bs
 * @date 2023-09-04
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CkBillNumberServiceImpl  extends MPJBaseServiceImpl<CkBillNumberMapper, CkBillNumber> implements ICkBillNumberService {
    @Resource
    private ICkBillNumberService ckBillNumberService;
    @Override
    public String getBillNumber(String billPrefix) {
        String billNo = "";
        if (StringUtils.isBlank(billPrefix)) {
            billPrefix = "DD";
        }
        LambdaQueryWrapper<CkBillNumber> query = new LambdaQueryWrapper<>();
        query.eq(CkBillNumber::getBillPrefix, billPrefix);
        String billDate = DateUtils.dateTimeNow("yyyyMMdd");
        query.eq(CkBillNumber::getBillDate, billDate);
        List<CkBillNumber> lsBill = ckBillNumberService.list(query);
        CkBillNumber billNumber = new CkBillNumber();
        if (lsBill != null && lsBill.size() > 0) {
            billNumber = lsBill.get(0);
            billNumber.setBillNumber(billNumber.getBillNumber() + 1);
        } else {
            billNumber.setBillDate(billDate);
            billNumber.setBillPrefix(billPrefix);
            billNumber.setBillNumber(1L);
        }
        ckBillNumberService.saveOrUpdate(billNumber);
        billNo = billPrefix + billDate + String.format("%04d", billNumber.getBillNumber());
        return billNo;
    }
}
