/**
 * BladeX Commercial License Agreement
 * Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
 * <p>
 * Use of this software is governed by the Commercial License Agreement
 * obtained after purchasing a license from BladeX.
 * <p>
 * 1. This software is for development use only under a valid license
 * from BladeX.
 * <p>
 * 2. Redistribution of this software's source code to any third party
 * without a commercial license is strictly prohibited.
 * <p>
 * 3. Licensees may copyright their own code but cannot use segments
 * from this software for such purposes. Copyright of this software
 * remains with BladeX.
 * <p>
 * Using this software signifies agreement to this License, and the software
 * must not be used for illegal purposes.
 * <p>
 * THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY. The author is
 * not liable for any claims arising from secondary or illegal development.
 * <p>
 * Author: Chill Zhuang (bladejava@qq.com)
 */
package org.springblade.zhaocai.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.zhaocai.mapper.BillCodeMapper;
import org.springblade.zhaocai.pojo.entity.BillCode;
import org.springblade.zhaocai.service.IBillCodeService;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 单据号码服务实现类
 *
 * @author Chill
 */
@Service
public class BillCodeServiceImpl extends ServiceImpl<BillCodeMapper, BillCode> implements IBillCodeService {

	/**
	 * 最大重试次数
	 */
	private static final int MAX_RETRY = 10;

	/**
	 * 单据号前缀
	 */
//	private static final String BILL_NO_PREFIX = "NDZC";

	@Override
	public String generateBillCode(String billType,String perFix) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
		for (int i = 0; i < MAX_RETRY; i++) {
			String dateStr = dateFormat.format(new Date());
			String randomStr = String.format("%03d", ThreadLocalRandom.current().nextInt(0, 1000));
			String candidate = perFix + dateStr + randomStr;
			if (baseMapper.selectCount(Wrappers.<BillCode>lambdaQuery()
				.eq(BillCode::getBillCode, candidate)) == 0) {
				BillCode billCode = new BillCode();
				billCode.setBillCode(candidate);
				billCode.setBillType(billType);
				billCode.setCreateTime(DateUtil.now());
				baseMapper.insert(billCode);
				return candidate;
			}
		}
		throw new ServiceException("单据号生成失败，请重试");
	}

}
