package com.cim.idm.utils;

import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.wmsextend.generic.errorHandler.CustomException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class CodeGenerator {

	private static Log log = LogFactory.getLog(CodeGenerator.class);

	private static final String DATE_FORMAT = "yyyyMMdd";
	private static final String PREFIX = "PT";
	public static String generateCode() throws CustomException {


		String currentDateStr = new SimpleDateFormat(DATE_FORMAT).format(new Date());
		String newPalletNo = null;
		boolean success = false;

		while (!success) {

			String maxSeqNoQuery = "SELECT NVL(MAX(TO_NUMBER(SUBSTR(PALLETNO, " +
					"(LENGTH('" + PREFIX + "') + LENGTH(:dateStr) + 1), 3))), 0) + 1 AS new_seq " +
					"FROM MATERIALPACKINGPALLET " +
					"WHERE SUBSTR(PALLETNO, 1, LENGTH('" + PREFIX + "') + LENGTH(:dateStr)) = '" + PREFIX + "' || :dateStr";

			try {
				log.info("maxSeqNoQuery: " + maxSeqNoQuery);
				Map<String, String> bindMap = new HashMap<String, String>();
				bindMap.put("dateStr", currentDateStr);
				Map<String, Object> maxSeqNoResult = IDMFrameServiceProxy.getSqlTemplate().queryForMap(maxSeqNoQuery,bindMap);

				int newSeqNo = 0;
				if (maxSeqNoResult != null && maxSeqNoResult.containsKey("new_seq")) {
					newSeqNo = Integer.parseInt(maxSeqNoResult.get("new_seq").toString());
				}
				// 确保流水码不超过999
				if (newSeqNo > 999) {
					throw new CustomException("流水码超过了数字999");
				}
				String newSeqNoStr = String.format("%03d", newSeqNo);
				newPalletNo = PREFIX + currentDateStr + newSeqNoStr;

				success = true;
			}catch (Exception e) {
				log.error("Failed to generate pallet number: " + e.getMessage());
				throw new CustomException("生成流水码错误: " + e.getMessage());
			}

		}
		return newPalletNo;
	}
}
