package com.scm.contract.tools;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.scm.contract.service.print.PrintCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * @author zuo
 * @date 2024/6/26 12:43
 */
@Component
public class MaterielSerialNumber {

    @Autowired
    private PrintCodeService printCodeService;

    private Map<String, Long> map;
//    private long sequence = 0L;

    public void into() {
        if (CollectionUtils.isEmpty(map)) {
            this.map = printCodeService.getMaxSerialNumber();
        }
    }

    public synchronized String generateId(String key) {
        Date date = new Date();
        Calendar ca = Calendar.getInstance();
        ca.setTime(date);
        int year = ca.get(Calendar.YEAR);
        key = key + "|" + year;
        Long serialNumber = map.get(key);
        if (Objects.isNull(serialNumber)) {
            serialNumber = 0L;
            map.put(key, serialNumber);
        }
        map.put(key, map.get(key) + 1);
        String number = String.format("%06d", map.get(key));
        return year + number;
    }
}
