package com.cim.idm.utils;

import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.mwmsextend.materialpacking.service.MaterialPackingServiceImpl;
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.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

// gf 生成流水码
@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;
	}

	// 修改数量，条码里批次拆分获取流水码
	public static String packingGenerateCode(String materialpackingname,String qty2,String Charge) throws CustomException {

		int sequence = 1; // 假设从1开始计数，实际中可能需要从数据库获取当前最大值或使用其他逻辑

		// 查询当前批次下的所有条码，获取最大流水码，并在最大流水码基础上加1
		String query = "SELECT MATERIALPACKINGNAME FROM MATERIALPACKING WHERE CHARGE = :CHARGE";

		try {

			Map<String, String> bindMap = new HashMap<String, String>();
			bindMap.put("CHARGE", Charge);
			List<Map<String, Object>> result = IDMFrameServiceProxy.getSqlTemplate().queryForList(query, bindMap);

			// 如果存在流水码（同批次下，除开原条码还有新的条码）
			if(result.size() > 1){

				// 存储流水码
				List<String> chargeNoList = new ArrayList<>();

				for (Map<String, Object> map : result) {
					String materialPackingName = map.get("MATERIALPACKINGNAME").toString();
					String[] partsPak = materialPackingName.split("\\|");
					if (partsPak.length < 7) {
						throw new IllegalArgumentException("条码格式有误: " + materialPackingName);
					}
					String[] chargeNos = partsPak[4].split("-");
					// 存在流水码的，最少能拆2个
					if(chargeNos.length > 1){
						// 获取chargeNos最后一个值（流水码）
						String lastValue = chargeNos[chargeNos.length - 1];

						// 正则匹配lastValue字符串的值，只能是1-9的单个字符串
						if (lastValue.matches("[1-9]")) {
							chargeNoList.add(lastValue);
						}
					}
				}
				//对储存的流水码chargeNoList，进行排序，获取最大流水码并加1赋值给sequence
				Collections.sort(chargeNoList);
				int max = Integer.parseInt(chargeNoList.get(chargeNoList.size() - 1));
				sequence = max + 1;
			}
//			else if (Charge.isEmpty()) {
//
//			}

			// 3. 遍历结果集，生成新条码并更新数据库
			List<Integer> idsToUpdate = new ArrayList<Integer>();
			List<String> newNames = new ArrayList<String>();

			String[] parts = materialpackingname.split("\\|");
			if (parts.length < 7) {
				throw new IllegalArgumentException("条码格式有误: " + materialpackingname);
			}

			// 构建新的条码部分，假设在第五部分（索引4，因为索引从0开始）后添加流水码
			StringBuilder newBasePart = new StringBuilder();
			for (int i = 0; i < parts.length - 4; i++) { // 不包括最后两个部分
				newBasePart.append(parts[i]).append("|");
			}

			// 辅材出库没有批次
			if(Charge.isEmpty()) {
//				生成一个新的批次
				LocalDate currentDate = LocalDate.now();
				DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
				String formattedDate = currentDate.format(formatter);
				List<String> boxIDs =  MaterialPackingServiceImpl.generateBoxID("LabelId", "SDK",
						1 + ""
						, formattedDate, "SH", "1010");
				// 打印boxIDs信息
				System.out.println("boxIDs:" + boxIDs + formattedDate);

				//生成3位随机数
				// 计算哈希值并取绝对值
				int hash = Math.abs(currentDate.toString().hashCode());
				// 取后3位（范围 000-999）
				int randomNumber = hash % 1000;
				// 确保结果为3位数（补零）
				String formatted = String.format("%03d", randomNumber);
				newBasePart.append(boxIDs.get(0)).append("-").append(formatted); // 在第五部分后添加流水码
			}else {
				newBasePart.append(parts[4]).append("-").append(sequence++); // 在第五部分后添加流水码
			}

//			for (int i = 6; i < parts.length; i++) { // 添加最后两个部分
//				newBasePart.append("|").append(parts[i]);
//			}
			// 添加倒数第二个部分（假设是日期）
			newBasePart.append("|").append(parts[5]);
			newBasePart.append("|").append(parts[6]);
			// 添加新的数量部分
			newBasePart.append("|").append(qty2); // 使用传入的新数量值

//			idsToUpdate.add(id);
			newNames.add(newBasePart.toString());

			return newBasePart.toString();

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

	}
}
